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?
humanandcatare subclasses ofcreatureyou could build your function to expect acreature, though I'm not experienced enough in C# to give you this as an example.varin 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'sdynamicto really get an open type, but for different reasons that's not something for beginners to use)