Michael
Michael

Reputation: 175

Accessing property

public class SomeClass<TElement>
{
    TElement _element;

    public void SomeFunction()
    {
        _element.Property = someValue;
    }

    public TElement Element 
    {
        get 
        {
            return _element;
        }
        set 
        {
            _element = value;
        }
    }
}

This is essentially what I want to do. The "TElement" in this class will always be a class that inherits from class containing "Property". I want to be able to access "Property" and modify it, and I want "SomeClass" to expose a property with the type "TElement". When I try to do this I cant access the properties as the "TElement does not contain a definition for...".

If I don't use "TElement", but the aformentioned class directly I don't know how to make the "Element" proprty appear as different types depeding on the instance.

Am I going about ths the wrong way? Could anyone point me in the right direction to get this type of functionality? Thanks

Upvotes: 1

Views: 79

Answers (3)

nodots
nodots

Reputation: 1490

public class SomeClass<TElement>
    where TElement : YourBaseClass
{ ... }

This is called a generic type constraint:

In a generic type definition, the where clause is used to specify constraints on the types that can be used as arguments for a type parameter defined in a generic declaration

Upvotes: 1

jeroenh
jeroenh

Reputation: 26772

You need a generic type constraint to express that TElement must have this Property: https://msdn.microsoft.com/en-us/library/Bb384067.aspx

For example:

public interface IHaveProperty
{
    string Property { set; }
}

public class SomeClass<TElement> where TElement : IHaveProperty
{

    TElement _element;

    void SomeFunction() 
    {
         // the generic constraint on TElement says that 
         // TElement must implement IHaveProperty, so you can
         // access Property here.
         _element.Property = string.Empty;
    }

}

Upvotes: 3

Aron
Aron

Reputation: 15772

public class SomeClass<TElement> where TElement : IProperty
{
    TElement _element;

    public void SomeFunction()
    {
        _element.Property = someValue;
    }

    public TElement Element 
    {
        get 
        {
            return _element;
        }
        set 
        {
            _element = value;
        }
    }
}
public interface IProperty
{
    SomeType Property { get; }
}

Upvotes: 2

Related Questions