Returning incorrect type from a function
Ok, I was scanning through some code yesterday and I saw this,
Code:
public class MyBaseClass
{
public string Field0()
{
return string.Empty;
}
}
public class MyClass : MyBaseClass
{
public string Field1()
{
return String.Empty;
}
}
Pretty simple no complaints there. In the main code,
Code:
private void Form1_Load(object sender, EventArgs e)
{
}
private MyBaseClass GetSomthing()
{
var retVal = new MyClass();
开发者_运维技巧 return retVal;
}
Now this code compiles correctly even though function GetSomthing() has a return type of MyBaseClass, it actually allows the return of MyClass(I assume that this is because of the inheritence).
I spotted this in somone elses code and to me it seems poor practice, although I may be missing somthing, anyone have any ideas?
Why is it poor practice? That's absolutely fine. For example, you might want:
public IEnumerable<string> GetNames()
{
return new List<string> { "Fred", "Jon", "Joe" };
}
It makes perfect sense from an encapsulation point of view - you're separating the interface of what you're willing to guarantee to the caller (it will be a sequence of strings) from the implementation (you're using a List<string>
). This lets you change the implementation later without disturbing callers.
It's good practice rather than poor practice.
An instance of MyClass
is also an instance of MyBaseClass
, so it is perfectly valid (and common) to do that...
精彩评论