Click here to Skip to main content
15,908,455 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
hi All,

what is difference between following 2 statement, i bit confused..
pls help..

1)declaring class variable like this

classA objA;
objA.Fun1();


2)and the other one, if i use it by this way..

classA objB = new classA();
objB.fun1();


thanx in advance..
Posted

1st one is just the declaration of variable. It is not instantiated. When you run it, you get 'Object reference is not set' or such error. 2nd one shows how to instantiate. It creates an object of classA and assigns it to objB.

Learn more by books/google.
 
Share this answer
 
Comments
Pravin Patil, Mumbai 17-Oct-11 7:52am    
you too deserve 5...
In the first case you have not intantiated the object. As a result, you only have access to the classes static methods.

Ine the second case, you are actually allocating a location for an instance in memory. You are actually creating an object of that class. This is what you would do in OOPS. Create objects and then set properties for each of these objets.

There is tons of information about this on the internet.
Something like this[^] should be good reading for you.
 
Share this answer
 
Comments
Prerak Patel 17-Oct-11 7:44am    
You beat me. +5
Abhinav S 17-Oct-11 7:55am    
Thanks Prerak.
Pravin Patil, Mumbai 17-Oct-11 7:52am    
very nice answer... +5
Abhinav S 17-Oct-11 7:55am    
Thank you Pravin.
when you declare a object like

C#
classA objA;

then object of a class is created with null reference

when you instantiate an object like

C#
classA objA = new classA()

then all the variables and methods of class is referenced to a object.
 
Share this answer
 
v2
Instantiation: the creation of an object (allocating memory for it).

declaration or initialisation: setting the default values.

C#
public class A
{
    int field1;
    public A()
    {
        // Start Initialization.
        field1 = 2;
        // End Initialization.
    }
    public void MyInit()
    {
        // Start Initialization.
        field1 = 1;
        // End Initialization.
    }
}

protected void Page_Load(object sender, EventArgs e)
{
    A a; // Object declaration

    // A "new" keyword means allocating memory for it 
    a = new A(); // Object Instantiation and Initialization

    // Another Initialization
    a.MyInit(); // Initialized by calling another method
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900