Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between variable and object

Tags:

c#

.net

Well, There are two statements occurred repeatedly in tutorials from where I'm learning C#.net

DataRow dr;

What does this mean. I assume it is a variable of DataRow class.

DataRow dr = new DataRow();

What does this mean. I assume it is an object of DataRow Class.

But still I left with an ambiguity that In which case I've to use 1st case Or 2nd Case. I'm quite confused now.

I assumed that this question has been repeated in Java forum. but I didn't get it as I don't have any background of Java. so before marking it repeat consider this.


1 Answers

Creating a variable has 2 parts, Declaration and Assignment.

In the Declaration part, you state that the variable exists and you state its type:

DataRow dr; // Create's a variable of type DataRow with a value of null.

The Assignment takes a value and point the variable to it:

dr = new DataRow(); // Creates a new DataRow and points dr variable to it.

You can do them both in the same line like that:

DataRow dr = new DataRow();

The result is the same as if you would separate those into the 2 lines above and the type of the variable is in both cases DataRow.

The object inside the variable however can be of an inherited type:

class MyDataRow : DataRow
{
}

DataRow dr = new MyDataRow(); //Creates a new object of type MyDataRow and points dr to it.

Managed objects must be held by a variable otherwise they are Garbage Collected.

like image 186
Tamir Vered Avatar answered May 04 '26 03:05

Tamir Vered



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!