Can we initialize an Object inside a block or function (without declaring it before) so that it can be used outside its block too…?
Here Type2 is a derived class from Type1
for eg:
if(a==b)
{ Type1 obj = new Type1();}
else
{Type2 obj = new Type2();}
obj.getFunction();
I have a base class USER derived class ADMIN, have to create an object according to the role of the user while he logs in and use that object afterwards so thath i dont need to check the role of the user every time.. (am a newbie)
IS THIS POSSIBLE??
The variable can only be of one type or another – otherwise how would the compiler know what member access to allow afterwards?
If there’s some common base type (base class or interface) which declares
function, that should be the type of the variable:This would be simpler as:
If they’re really different types, so you’re effectively calling entirely separate methods, then either you’ll need to declare the variable within each block and call the method there, or if you’re using C# 4 or later you could use dynamic typing:
You should really be trying to think about whether this is a genuinely-common function, in which case it should be declared in a base type, or whether it’s just a coincidence that you’ve got two functions with the same name, in which case trying to treat them the same way is a bad idea. (Imagine you refactor one type to change the method name, for example…)