Matt West
Matt West

Reputation: 1396

How to create a method that takes a generic class as a parameter

I've been searching S.O and elsewhere for an answer to this question, and I can't find one that is helping me understand my problem. I'm new to C#, so that might be part of the issue.

I'm trying to get a handle on how to pass a class (or a copy of one) as a parameter to a method. However, I want this method to accept any class I pass it, not a specific one.

So for instance:

class Person
{
    public string Name{ get;set; }
}

class Bob : Person
{
    public Bob(){ Name = "Bob"; }
}

class Fred : Person
{
    public Fred(){ Name = "Fred"; }
}

Fred aFred = new Fred();
Bob aBob = new Bob();

// below is where I need the help, I don't know the syntax for what I'm trying to do.
SayName(aBob,aFred);

static public void SayName(person1,person2)
{
    Console.WriteLine(person1.Name + ", " +person2.Name) // I'd like this to output "Bob, Fred"
}

Okay, I know that above syntax isn't correct insofar as passing those classes as parameters or in accepting them as arguments for the method, but I'm hoping that you can see what I'm trying to do. I'd like to be able to pass any class deriving from Person to the SayName method, and have it output whatever its name happens to be.

Thanks in advance, any help is appreciated.

Is there a way to do this?

Upvotes: 2

Views: 140

Answers (2)

balaji the marvel
balaji the marvel

Reputation: 43

Type is not declared as parameters in SayName, seems to be a misunderstanding in understanding how to pass parameters. Use Person type for both parameters say person1 and person 2 the code will run

public static void SayName(Person person1, Person person2)
{
    Console.WriteLine(person1.Name + ", " +person2.Name)
}

Upvotes: 0

Dmitry
Dmitry

Reputation: 14059

Just pass them as Person:

static public void SayName(Person person1, Person person2)
{
    Console.WriteLine(person1.Name + ", " +person2.Name) // I'd like this to output "Bob, Fred"
}

Upvotes: 8

Related Questions