The below is the C# implementation for the a function for given parameters `int a`, `int b` - both represent characters 'A' and 'B' respectively, where the function should return a string containing both characters 'A' and 'B' occurring `a` times and `b` times respectively but neither 'A' nor 'B' repeating consecutively for more than 2 times. Both values for `a` and `b` are given in a way that a string can be build using those numbers - so eg: `Foo(0,3)` or `Foo(1,7)` shall not be invoked.

eg: 

`Foo(3,3)` returns "`BBAABA`" or "`AABBAB`"

`Foo(4,1)` returns "`AABAA`"

`Foo(3,5)` returns "`BAABBABB`" or "`BBAABBAB`"

Code:


    static string Foo(int a, int b)
    {
    	int total = a + b;
    	StringBuilder sb = new StringBuilder();
    	char charToPrint = a > b ? 'A' : 'B';
    	int flag = 0;
    
    	for(int x =0; x< total; x++)
    	{
    		if(flag == 2)
    		{
    			flag = 0;
    			charToPrint = SwapChar(charToPrint);
    		}
    		if(charToPrint == 'A' && a == 0 || charToPrint == 'B' && b == 0)
    		{
    			charToPrint = SwapChar(charToPrint);
    		}
    
    		if (charToPrint == 'A')
    			a--;
    		else
    			b--;
    
    		sb.Append(charToPrint);
    		flag++;
    	}
    	return sb.ToString();
    }

    static char SwapChar(char thisChar)
    {
        return thisChar == 'A' ? 'B' : 'A';
    }

This is working but I would like to receive some feedback on this code.