Methods with classname as a return type

前端 未结 2 825
鱼传尺愫
鱼传尺愫 2021-01-29 03:35

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

相关标签:
2条回答
  • 2021-01-29 04:26

    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.

    0 讨论(0)
  • 2021-01-29 04:26

    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 Triangles, 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.

    0 讨论(0)
提交回复
热议问题