Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate exception: method Add should be 'public/protected virtual' or 'protected internal virtual'

Take this class as example:

public class Category : PersistentObject<int>
{
    public virtual string Title { get; set; }
    public virtual string Alias { get; set; }

    public virtual Category ParentCategory { get; set; }
    public virtual ISet<Category> ChildCategories { get; set; }


    public /*virtual*/ void Add(Category child)
    {
        if (child != null)
        {
            child.ParentCategory = this;
            ChildCategories.Add(child);
        }
    }
}

When running the application without the virtual keyword of add method, I getting this error:

method Add should be 'public/protected virtual' or 'protected internal virtual'

I understand why properties need to declare as virtual, because thay need to be overridden by the lazy loading feature.

But I don't understand why Methods need to be declare as virtual... they need to be overridden for what reason?

This very confusing!

like image 820
Fitzchak Yitzchaki Avatar asked Feb 17 '10 03:02

Fitzchak Yitzchaki


1 Answers

Methods as well need to be virtual because they could access fields. Consider this situation:

class Entity
{

  //...
  private int a;
  public virtual int A 
  { 
     get { return a; }
  }

  public virtual void Foo()
  {
    // lazy loading is implemented here by the proxy
    // to make the value of a available
    if (a > 7) 
    // ...
  }
}
like image 62
Stefan Steinegger Avatar answered Oct 19 '22 02:10

Stefan Steinegger