3

There are 2 classes - a base class, and inherited class. I want the function print to be able print objects of both of these classes. Though the name of the function is similar in both cases, the signature of the function is different. Why then the function does not work here?

this is the code:

using System;

namespace ConsoleApp8
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Asset asset = new Asset();     // פולימורפיזם
            asset.name = "A";
            asset.price = 1;

            Stock stock = new Stock();
            stock.name = "B";
            stock.price = 2;
            stock.shared = 5;

            print(stock);
            print(asset);

            static void print(Asset asset)
            {
                Console.WriteLine(asset.price + " " + asset.name);

            }
            static void print(Stock stock)
            {
                Console.WriteLine(stock.price + " " + stock.name + " " + stock.shared);
            }
        }

        class Asset
        {
            public string name;
            public int price;
        }
        class Stock : Asset
        {
            public int shared;
        }
    }
}


Thank you!

StepUp
  • 36,391
  • 15
  • 88
  • 148
  • 3
    Local functions don't support overloading. There's probably a duplicate question somewhere... – Sweeper Jun 17 '22 at 16:47
  • In your own words: does the definition of `static void print(Asset asset)` appear *inside* `static void Main(string[] args)`, or *outside*? Why? *Should* it be inside, or outside? Why? – Karl Knechtel Jun 17 '22 at 16:47
  • Is there any reason you chose not to override `ToString()` on `Asset` and `Stock`? – nullforce Jun 17 '22 at 16:49
  • Not an exact duplicate, but mentions the the fact that local functions don't support overloading: https://stackoverflow.com/questions/71279242/net-6-how-to-use-method-overloading-in-console-app-startup – Sweeper Jun 17 '22 at 16:51
  • Feel free to ask any question. If you feel that my reply is helpful, then you can upvote or mark my reply as an answer to simplify the future search of other users. [How does accepting an answer work?](https://meta.stackexchange.com/a/5235/309682) – StepUp Jun 22 '22 at 03:36

1 Answers1

4

Local functions cannot be overloaded:

A method cannot contain two local functions with the same name but different parameters. That is, overloaded local functions are not supported.

So what you can do is to create two local methods with different names:

void PrintAsset(Asset asset) {}
void PrintStock(Stock stock) {}

And some more restrictions for local functions:

  • local functions can't be virtual or abstract
  • (related) local functions can't be marked override or sealed
  • local functions can't have access modifiers
StepUp
  • 36,391
  • 15
  • 88
  • 148