Ber53rker
Ber53rker

Reputation: 1038

Return instance of unknown class?

OK, so, I may be nuts but is it possible to return a value of an unknown type and have it get functions?

Basically a function that looks like...

public static ?????? Test(char c)
{
    if(c == char)
        return instance of SOMECLASS
    else
        return instance of SOMEOTHERCLASS
}

// so i could do
Test(new char()).SOMECLASS_METHOD();
Test(new int()).SOMEOTHERCLASS_METHOD();

Please & Thanks

EDIT: Just to add, is there a way to also make it appear in intellisense?

Upvotes: 1

Views: 480

Answers (2)

user586399
user586399

Reputation:

public static object Test(char c)
{
    if(c == char)
        return instance of SOMECLASS
    else
        return instance of SOMEOTHERCLASS
}

// so i could do
var r = Test(new char());
if (r is SOMECLASS)
   (r as SOMECLASS).SOMECLASS_METHOD();
var rr = Test(new int());
if (rr is SOMEOTHERCLASS)
   (rr as SOMEOTHERCLASS).SOMEOTHERCLASS_METHOD();

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564413

You can return dynamic (in C# 4 or later), which lets you use dynamic binding.

That will let any method be written, and only fail at runtime if the method (or property) doesn't exist on the object.

For example, you can write:

class Foo { 
   void Bar() { Console.WriteLine("Foo.Bar"); }
}

class Bar { 
   void Baz() { Console.WriteLine("Bar.Baz"); }
}

public static dynamic Test(char c)
{
   if (c == 'f') return new Foo();
   else return new Bar();
}

With that, you could write:

Test('f').Bar();
Test('q').Baz();
Test('z').Bar(); // Will raise exception at runtime

Upvotes: 4

Related Questions