Sealer_05
Sealer_05

Reputation: 5576

Shorter way to create datacontext object?

I have a very simple question and would be great if someone could save me some typing in the future.

I see myself typing this statement often:

using (DataClasses1DataContext db = new DataClasses1DataContext())

I remember seeing a shorter version of it somewhere but can seem to find it. I believe it has the name of the datacontext only typed once.

Thanks!

Upvotes: 4

Views: 504

Answers (3)

Paul Sasik
Paul Sasik

Reputation: 81547

Like this?

using (var db = new DataClasses1DataContext())

To abbreviate it even further you could do something like this:

using (var db = DataClass.DB()) 

Where DataClass has a static method DB that returns a new instance of your data context.

Upvotes: 5

Travis J
Travis J

Reputation: 82337

I still have to do this too, usually in a repository. The only difference as others answered is to use the var db implicit definition. This works because you are instantiating a class explicitly with the new keyword so the compiler still knows that the type will be DataClasses1DataContext

Upvotes: 2

empi
empi

Reputation: 15901

using (var db = new DataClasses1DataContext())

Upvotes: 3

Related Questions