c# - A field initializer cannot reference the non-static field, method, or property? -


i have repository class , services class below :

public class dinnerrepository {     dinnerdatacontext db = new dinnerdatacontext();      public dinner getdinner(int id)     {         return db.dinners.singleordefault(d => d.dinnerid == id);        }  // others code         }    public class service {         dinnerrepository repo = new dinnerrepository();          dinner dinner = repo.getdinner(5);  // other code } 

this throws error:

a field initializer cannot reference non-static field, method, or property.

even though have intatiated dinnerrepository class expose method getdinner() in service class. works fine below code. there alternative or standard practice? cannot use static methods here..

public class service {      public service()     {         dinnerrepository repo = new dinnerrepository();          dinner dinner = repo.getdinner(5);     }  } 

personally i'd initialize fields in constructor:

public class service {     private readonly dinnerrepository repo;     private readonly dinner dinner;      public service()     {         repo = new dinnerrepository();         dinner = repo.getdinner(5);     } } 

note isn't same code show @ bottom of question, that's declaring local variables. if want local variables, that's fine - if need instance variables, use code above.

basically, field initializers limited in can do. section 10.5.5.2 of c# 4 spec:

a variable initializer instance field cannot reference instance being created. compile-time error reference this in variable initializer, because compile-time error variable initializer reference instance member through simple-name.

(that "thus" , "therefore" looks wrong way round me - it's illegal reference member via simple-name because references this - i'll ping mads - that's relevant section.)


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -