is null allowed in C#?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

Is null value for a class instance allowed in C#? for example:
MyClass obj = null;

If Not, how to initiate an instance with value 0? How to detect if an
instance is "newed" ? And how to pass a null value to a class constructor
whch has a object paramer can be 0?

In general, how C# handle a pointer with value 0;

Thanks
 
Hi there...

In your first sample ur definining an object (variable) but not creating it.
You know it's "newed" cuz obj != null
Yes it's possible to pass null to a constructor... for example

using System;

class Test {
static void Main() {
MyClass x = new MyClass(null);
Console.WriteLine("MyClass::Member is " + ((object) (x.Member !=
null ? "Not null" : "Null")).ToString());
Console.ReadLine();
}
}


class MyClass {
private object m_member;

public object Member {
get {return m_member;}
}

public MyClass(object arg) {
m_member = arg;
}
}


Regards,
 
Fei Li said:
Is null value for a class instance allowed in C#? for example:
MyClass obj = null;

obj is a variable, not a class instance. null is effectively something
saying, "This value isn't a reference to a class instance at all. It's
a reference to no object."
If Not, how to initiate an instance with value 0?

What do you mean "with value 0"?
How to detect if an instance is "newed" ?

If a reference is non-null, it's a reference to an instance.
And how to pass a null value to a class constructor
whch has a object paramer can be 0?

Just pass null.
In general, how C# handle a pointer with value 0;

null is a special reference. You can possibly think of it as a pointer
with value 0, but it's better not to think in those terms - just think
of it as a reference meaning "No object".
 
Back
Top