casting an object whose value is null

jargoman

Member
Joined
Dec 19, 2013
Messages
7
Programming Experience
3-5
Is this valid code given getDog returns either a (Object)Dog or (Object)null ? It makes my code so much easier if so

C#:
public Object getDog() {
    .......
    if (noDogsFound) {
       return null;
    }
}

....

Dog dog = (Dog) getDog();  // casting a null object to type Dog

if (dog != null) {
     ...dosomething();
}
 

jargoman

Member
Joined
Dec 19, 2013
Messages
7
Programming Experience
3-5
unfortunately that's not an option. The code I provided is only an example. The read code is more complicated and could return a number of objects depending on parameters.

C#:
enum Animal {DOG, CAT, INT, LONG};

Dod d = (dog)getObject(DOG); // guaranteed to return a dog but may also return null
Cat c = (Cat) getObject(CAT);
int i = (int) getObject(INT); // returns 0 and not null so this isn't an issue
I suppose it's no big deal I could do this

C#:
object o = getObject(DOG);
if (o!=null) {d = (Dog)o;}
else {d = null}
But it's harder to read.
 

jmcilhinney

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
3,144
Location
Sydney, Australia
Programming Experience
10+
You should probably be doing something like this:
var result = GetObject();
Dog d;
Cat c;

if (result == null)
{
    // There is not object.

    return;
}

d = result as Dog;

if (d != null)
{
    // The object is a Dog instance;

    return;
}

c = result as Cat;

if (c != null)
{
    // The object is a Cat instance;

    return;
}
 
Top Bottom