Struct (Value Types)

Discussion in 'C#' started by Programmer.Nick, Dec 21, 2006.

  1. Programmer.Nick

    Programmer.Nick New Member

    Joined:
    Dec 19, 2006
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0

    Introduction



    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:
    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.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice