Reputation: 67
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?
Upvotes: 1
Views: 656
Reputation: 76
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);
}
}
Upvotes: 1
Reputation: 1064114
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!
Upvotes: 6