1

Is there a possibility to pass object in c# the same way as I can do it in Javascript in generic way? How can I achieve this in c#? Since all variables need to be declared but they have different class names.

class human {
  constructor() {
    this.name = "John";
  }
}

class cat {
  constructor() {
    this.name = "Garfield";
  }
}


 function showName(character) {
    console.log("My name is: " + character.name)
  };

var character1 = new cat();
var character2 = new human();

showName(character1)
showName(character2)

I want to make same showName as one function but c# require to declare class names like:

public void ShowName(Human human) {}
public void ShowName(Cat cat) {}

How will look example code that I can achieve this in c# like in JS?

Scoppex
  • 57
  • 4
  • I don't think so. C# is highly type hinted and you always have to know the type of the variable. The most generic is var – Combinu May 09 '21 at 17:39
  • Well, since Javascript is not known for being a typed language, I don't think it is possible. For type security related stuff, you should check TypeScript out instead. – IncroyablePix May 09 '21 at 17:39
  • If both `human` and `cat` are subclasses of `creature` you could build your function to expect a `creature`, though I'm not experienced enough in C# to give you this as an example. – LaytonGB May 09 '21 at 17:45
  • @Combinu: The keyword `var` in C# does not declare a generic type or an open type. It just tells the compiler that he should derive the type from the righthand side of the expression. The result is exactly the same as if the concrete type was used. (there's `dynamic` to really get an open type, but for different reasons that's not something for beginners to use) – PMF May 09 '21 at 19:08

2 Answers2

5

To do this in C# you'd either need to use a common base-class or interface (perhaps IHasName with a string Name {get;} property, and declare the parameter as IHasName, and declare that both Human and Cat implement IHasName), or you can throw all reason to the wind and declare the parameter as dynamic, for that JavaScript feel. Please do the first, not the second!

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

You can use inteface to achieve it. Interface gives abstarction for those class which are implemented based on it and you can use interface in arguments of method. See this example:

public interface IBeings
{
    public string Name { get; set; }
}

public class Human : IBeings
{
    public string Name { get; set; }
}

public class Cat : IBeings
{
    public string Name { get; set; }
}

class Program
{
    static void ShowName(IBeings being)
    {
        Console.WriteLine($"My name is: {being.Name}");
    }

    static void Main(string[] args)
    {
        Human human1 = new Human() { Name = "John" };
        Cat cat1 = new Cat() { Name = "Kitty" };

        ShowName(human1);
        ShowName(cat1);
    }
}