James
James

Reputation: 67

C#: Implement an Interface witha Property of Any Type

I'm trying to implement an interface that requires a single property, but I don't explicitly care what type it is. For example:

public interface IName
{
    dynamic Name {get; set;}
}

Then if I have a class I'd like to implement the IName interface with a type of string:

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

This however raises an error. I know I could make the interface IName take a generic arguement IName<T> but that forces me to create a bunch of overloaded functions that take IName<string>, IName<NameObj>, IName<etc> instead of casting within a single function.

How can I require that a class contains a property?

Upvotes: 3

Views: 7543

Answers (4)

mgronber
mgronber

Reputation: 3419

I am unable to test this now, but maybe you could implement the interface explicitly.

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

    dynamic IName.Name {
        get { return this.Name; }
        set { this.Name = value as string; }
    }
} 

Upvotes: 5

helloworld922
helloworld922

Reputation: 10939

Returning a dynamic allows you to return any type you please. Simply declare the type in your implementing class to be dynamic.

    public interface IName
    {
        dynamic name { get; set; }
    }

    public class Person: IName
    {
        private string _name;
        public dynamic name { get { return _name; } set { _name = value;} }
    }

edit:

note that you'll have to be careful about what you pass to name since the type of value will only be checked at runtime (the joys of using dynamic types).

Person p = new Person();
p.name = "me"; // compiles and runs fine, "me" is a string
p.name = p; // compiles fine, but will run into problems at runtime because p is not a string

Upvotes: 1

KBBWrite
KBBWrite

Reputation: 4409

Make

public string Name {get; set;}

and make the return type Object.

Upvotes: 0

Cheng Chen
Cheng Chen

Reputation: 43503

interface IName<T>
{
    T Name { get; set; }
}

class Person : IName<string>
{
    public string Name { get; set; }
}

Upvotes: 13

Related Questions