Click here to Skip to main content
15,891,682 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
static unsigned int i = (unsigned short)((signed short)GetTickCount());
       if( ~i  & 2 )
       {
           i+=3U;
       }
       else
       {
           i+=5U;
       }

this is some c++ code which i want to convert it to c# plz help

What I have tried:

uint i = GetTickCount();

                if( ~i  & 2 )
                {
                    i+=3U;
                }
                else
                {
                    i+=5U;
                }
Posted
Updated 15-Nov-17 21:49pm

The only significant difference I see is the static on the original - which has no equivelant in C#.
In C and C++ a static local variable is scoped to the function, but the value is not stack based - it is preserved across executions of the method so if you change it this time it will have the new value next time the function is called. C# does not have anything like that, so your variable would have to be declared at class level, with or without the static keyword depending on the method declaration.

But generally, converting C or C++ code directly to C# is a bad idea: you do not end up with "good C#". Rewriting it to use C# features and .NET classes is normally a much better idea.
 
Share this answer
 
The GetTickCount() call is used to get a random start value stored in a static variable (it is only called once at program start). The casting to short will limit the value to 16 bits (ignore the higher bits).

You can create a static class and also use the C# Random class for similar behaviour :
C#
public class MyClass
{
    static int i;
    static MyClass()
    {
        i = Environment.TickCount() & 0xffff;
        // Or
        //Random random = new Random();
        //i = random.Next(0, 0xffff);
    }
    void DoIt()
    {
       if( ~i  & 2 )
       {
           i+=3U;
       }
       else
       {
           i+=5U;
       }
    }
};
 
Share this answer
 
That should work but you left out the static qualifier. This results in the C++ code is that the code is only executed once, what I would call a smell or a bug. I dont know your code, but I think the static is wrong.

BTW: In the C++ code you cap the tick count to a unsigned short and so loose the higher bits, but you dont need them for your if.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900