Reputation: 87
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 common structure is
<modifier><return type><method name>()
{
//do any thing
return <abc which should same as return type which declared above>;
}
in above said example I saw many times in <return type>
use of <class name>
, <dictionary>
etc.
but natural these are also user defined types. so this also should be here. But, never stood what happened actually here when we use "class name" in place of string or any data type?
Please let me understand this with easy words, and easy examples.
class StockData
{
public int StockID { get; set; };
public double CurrentPrice { get; set; };
public string StockName { get; set; };
}
class GetStock
{
public StockData /*(this is the same name which is the class name above)*/ GetStockData(string symbol)
{
//something
return /*(what will be the return type?)*/;
}
}
Upvotes: 1
Views: 3798
Reputation: 28097
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.
Upvotes: 1
Reputation: 1668
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.
Upvotes: 1