Go4Expert (http://www.go4expert.com/)
-   C# (http://www.go4expert.com/articles/c-sharp-tutorials/)
-   -   Struct (Value Types) (http://www.go4expert.com/articles/struct-value-types-t2315/)

Programmer.Nick 21Dec2006 16:00

Struct (Value Types)


Classe Will be used to implement most objects.
Somtimes however, it may be desirable to create an object that behavves like one of the references. in that case, a value type used, wich is done by declaring a Struct in C#.

structs act similarly to classes, but with a few added restrictions. they can't inherit form any other type (thought they implicitly inherit form Object), and other classes can't inherit from them.

A point struct

In a graphics system, a value class could be used to encapsulate a point.
Here's how it would be declared

Code: CSharp

using System;

struct point
    public point(int X, int Y)
        this.X = X;
        this.Y = Y;
    public override string ToString()
        return (string.Format("({0},{1})", X, Y));
    public int X;
    public int Y;
class test
    public static void main()
        point start = new point(5, 5);
        Console.WriteLine("Start : {0}", start);

The X and Y componets to the point can be accessed in the Main() function, a point is created by usint the new .
for value types,new create an object on the stack and then calls the appropriate constructor.

In the Console.writeline() we type the value or Start, and its (5,5)

well thats it today, I hope you now knows a lil' bit about the Constructor and the use for it.

All times are GMT +5.5. The time now is 03:30.