Why we need a struct? When to use it?


i'm rookie in c#, was reading demo projects recently , found modle class, , don't konw why need struct, it seems same class. difference them? why need use struct?

hello,

main difference structs passed\copied value , classes passed\copied reference

i wrote demo illustrate statement. please have look

here "pointclass"

class pointclass     {                    public int x,y;             public pointclass(int x,int y)             {                 this.x = x;                 this.y = y;             }     }

in main class

class program { public struct pointstruct { public int x,y; public pointstruct(int x, int y) { this.x = x; this.y = y; } } static void main(string[] args) { pointstruct structpoint = new pointstruct(); structpoint.x = 10; structpoint.y = 10; console.writeline("initial struct value " + structpoint.x + "," + structpoint.y); modifystructpoint(structpoint); console.writeline("after modifystructpoint,struct value " + structpoint.x + "," + structpoint.y); pointclass classpoint = new pointclass(10,10); console.writeline("initial class value " + classpoint.x + "," + classpoint.y); modifyclasspoint(classpoint); console.writeline("after modifyclasspoint,class value " + classpoint.x + "," + classpoint.y); console.read(); } static void modifystructpoint(pointstruct mystruct) { mystruct.x = 20; mystruct.y = 20; console.writeline("inside modifystructpoint()"); console.writeline("struct after modify " + mystruct.x +","+ mystruct.y); } static void modifyclasspoint(pointclass myclass) { myclass.x = 20; myclass.y = 20; console.writeline("inside modifyclasspoint()"); console.writeline("class after modify " + myclass.x + "," + myclass.y); } }

after execute program, shows below

have nice day!

kristin





Visual Studio Languages  ,  .NET Framework  >  Visual C#



Comments

Popular posts from this blog

Azure DocumentDB Owner resource does not exist

How to Share webservice object to all user

BizTalk Server 2013 Azure VM Log Shipping and HA for hosts