Constructor Question?

Discussion in 'C#' started by shah123, Apr 3, 2007.

  1. shah123

    shah123 New Member

    Joined:
    Mar 27, 2007
    Messages:
    84
    Likes Received:
    0
    Trophy Points:
    0
    Hi,

    I am going to ask a question which is small bit silly but for me not as i want to grasp this information in mind.

    The question is i have seen samples of different codes which have as following
    Code:
    [B]Class A
    {
    int [] arr=new int[5];
    public A()
    {
    arr={1,8,96,6,3} ;
    }
    public static meth()
    {
    //code
    }[/B]
    I dont understand few things in it e.g.

    1. Why needed to constructor
    2. Why we define array in class and initialize in Constructor?

    Code:
    [B]Class B
    {
    int [] arr=new int[5];
    public B(int i,int j)
    {
    int lo=i;
    int hi=j;
    }
    public static meth()
    {
    //code
    }[/B]
    
    In Class B:

    3. Why we pass paramreters and assign to local variables what we think when we do that?


    Can you please answer my questions in nice way instead of being angry on my silly questions.I want to undertand this concept fully when to do or not to do like this?

    Thanks,
    Regds,
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,376
    Likes Received:
    388
    Trophy Points:
    83
    To initialize the member variables
    Thats what the task of the constructor is.
    To initialize the members with the values we have from the external functions (where we are creating the object).

    I guess you need some more info about the constructors and I will provide them for you.

    In OOP, a constructor in a class is a special block of statements called when an object is created, either when it is declared. A constructor is similar to a class method, but it differs from a method in that it never has an explicit return type, it's not inherited, and usually has different rules for modifiers. Constructors are often distinguished by having the same name as the declaring class. Their responsibility is to pre-define the object's data members.
     
  3. shah123

    shah123 New Member

    Joined:
    Mar 27, 2007
    Messages:
    84
    Likes Received:
    0
    Trophy Points:
    0
    Thanks Shabbir. Thanks a million
     

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