I had an interview where I was asked the following:
Question: A method with same name and signature but different return type. Is it possible and what is this type c
In C#, you cannot have methods like
int Foo() { return 1; }
void Foo() { return; }
They must vary by more than return type.
If the arguments are different, then you're good to go.
int Foo(string x) { return 1; }
void Foo(double x) { return; }
Though return type covariance is not supported in C#, it is possible to emulate it by using explicit implementation and method hiding. That is a pattern which is used thoroughly in the ADO.NET APIs.
E.g.:
public interface ISomeValue { }
public abstract class SomeValueBase : ISomeValue { }
public class SomeValueImpl : SomeValueBase { }
public interface ISomeObject { ISomeValue GetValue(); }
public abstract class SomeObjectBase : ISomeObject
{
ISomeValue ISomeObject.GetValue() { return GetValue(); }
public SomeValueBase GetValue() { return GetValueImpl(); }
protected abstract SomeValueBase GetValueImpl();
}
public class SomeObjectImpl : SomeObjectBase
{
protected override SomeValueBase GetValueImpl() { return GetValue(); }
public new SomeValueImpl GetValue() { return null; }
}
By doing that, the net result of calling GetValue()
is that it will always match the most specific available type.
You can do it whit interface
public interface IMyInterface
{
int Metoda1()enter code here`;
}
public class MyClass : test.IMyInterface
{
public IMyInterface Metoda1()
{
return new MyClas();
}
int test.IMyInterface.Metoda1()
{
return 1;
}
}
static void Main(string[] args)
{
MyClass instance = new MyClass();
IMyInterface inst = instance.Metoda1();
/* IMyInterface ints2 = inst.Metoda1(); //will not compile*/
Console.WriteLine(inst.GetType().ToString()); ;
object inst3 = inst.Metoda1();
Console.WriteLine(inst3.GetType().ToString());
}