DontVoteMeDown
DontVoteMeDown

Reputation: 21465

Accessing generic object parameter

Consider the following snippet:

public class FooRepository<T> : BaseRepository<T>
    where T : EntityBase
{
    public FooRepository(ISessionFactory sessionFactory)
        : base(sessionFactory)
    {
        this.AfterWriteOperation += (sender, local) => this.Log();
    }

    public void Log()
    {
        // I want to access T here
    }
}

I want to access T inside the Log() function but the problem is that I can't change the constructor signature, like: FooRepository(ISessionFactory sessionFactory, T entity). I don't know how to pass it into Log().

Is there another way?

UPDATE:

I want to access the instance of T inside Log().

UPDATE 2:

Well, sorry for the mess. I'm not used to all this stuff. I will try to clarify things here. So my repository is called in the Service layer:

BarRepository.Update(entityToPersist); // Bar inherits from Foo

Inside the Update method the event AfterWriteOperation is called:

if (AfterWriteOperation != null)
    AfterWriteOperation(this, e);

With all those things I just let away the simple fact that e in above case is my entity, so I can pass it to Log this way:

(sender, local) => this.Log(local); // I will rename local to entity

And get it inside the method.

Upvotes: 1

Views: 377

Answers (2)

ta.speot.is
ta.speot.is

Reputation: 27214

like void Log(T entity) and use it inside the method.

Well just do that:

using System;

namespace Works4Me
{
    public interface ISessionFactory { }
    public class EntityBase { }
    public class BaseRepository<T> where T : EntityBase { }

    public class FooRepository<T> : BaseRepository<T>
        where T : EntityBase
    {
        public FooRepository(ISessionFactory sessionFactory)
        {
        }

        public void Log(T entity)
        {
        }
    }

    public class Test
    {
        public static void Main()
        {
        // your code goes here
        }
    }
}

Success #stdin #stdout 0.01s 33480KB

With regards to your other statement:

I want to access the instance of T inside Log().

T in and of itself has no instance. You get can the Type object representing T with typeof(T).

Upvotes: 4

MrWombat
MrWombat

Reputation: 649

If you want to get information about the type e.g. Name, Methods, Interfaces, ... then use typeof(T) in log - thats like the .GetType() call on an instance and will return the type of the generic parameter. If you want to work with any instance of the type, you have to

a) create an instance (Activator.CreateInstance(typeof(T))) or

b) pass the instance via the constructor and then to the this.Log(passedInstance) call.

Upvotes: 1

Related Questions