Thursday, July 9, 2009

How can I define a structure in C#?

It's very easy:





struct MyStruct


{


float x;


float y


};





That was that simple!

How can I define a structure in C#?
C# does not have the concept of structure the way C or C++ has. Actually, any class or struct could be assumed to be a structure. C# has two kinds of classes: reference class which is formed as a reference object (similar to C pointers or C++ pointers or references) in the garbage-collected heap of the system, and struct which is a value class and is formed in the static data area or stack. struct data type is more useful for mathematical abstract data types or objects with small data field while classes are more useful for objects with larger data. structs and classes differ only in the definition keyword, and may be other minor things; for example, a struct may not have a default constructor like the way a class could have.
Reply:like this:





struct MyStruct


{


public int x;


public int y;


}





MyStruct ms = new MyStruct();


ms.x = 10;


ms.y = 20;
Reply:public struct MyStruct


{


// Field(s)


private int myNumber;





// Method(s)


public int WhatsMyNumber()


{


return myNumber;


}


}


No comments:

Post a Comment