I\'m new in c# or any type of programming language. When I see codes in c# I found there are lot of confusions are over here. one of them I want to clarify from here. Methods co
In GetStockData
method return type would be StockData
i.e. you will have to return an instance of StockData
class or any sub-class inherited from StockData
. It depends on your code whether you create that instance in the GetStockData
method or get from some other method, but surely type of the instance should be StockData
or any sub-class inherited from StockData
class.
So if we have a class Triangle
and a method GetTriangle
which has the parameter isBlue
.
public class Triangle
{
public string Colour { get; set; }
}
public Triangle GetTriangle(bool isBlue)
{
Triangle resultTriangle;
if (isBlue)
{
resultTriangle = new Triangle { Colour = "Blue" };
}
else
{
resultTriangle = new Triangle { Colour = "Red" };
}
return resultTriangle;
}
We can call GetTriangle
with an argument of true
or false
like so:
Triangle blueTriangle = GetTriangle(true);
Triangle redTriangle = GetTriangle(false);
Both of the results of GetTriangle
are Triangle
s, even though they contain different data (in this case a different Colour
).
Like a child's wood-block toy, the compiler checks what the "shape" of the data is, not what colour it is. So if you try to return a Square
from a method which returns Triangle
then the compiler will throw an error in the same way you wouldn't be able to put a square block in a triangle hole.