.net - What is 'this' used for in C# language? -
i've read open source c# code , there lot of strange grammar (to me).
they declare method arguments this keyword this:
this object @object
what mean?
if remove 'this' keyword before data type, work differently?
sounds extension method.
the @ symbol allows variable name same c# keyword - tend avoid them plague personally.
if remove this keyword, no longer extension method, static method. depending on calling code syntax, may no longer compile, example:
public static class integermethods { public static int add(this int i, int value) { return + value; } } int = 0; // "extension method" call, , compile against extension methods. = i.add(2); // standard static method call. = integermethods.add(i, 2); the compiler translate "extension method calls" standard static method calls @ rate, extension method calls still work against valid extension methods per this type name syntax.
some guidelines
these own, find useful.
- discoverability of extension methods can problem, mindful of namespace choose contain them in. have very useful stuff under .net namespaces such
system.collectionsor whatever. less useful otherwise "common" stuff tends go underextensions.<namespace of extended type>such discoverability @ least consistent via convention. - try not extend used types in broad scope, don't want
myfabulousextensionmethodappearing onobjectthroughout app. if need to, either constrain scope (namespace) very specific, or bypass extension methods , use static class directly - these won't pollute type metadata in intellisense. - in extension methods, "this" can
null(due how compile static method calls) careful , don't assume "this" not null (from calling side looks successful method call on null target).
these optional , not exhaustive, find fall under banner of "good" advice. ymmv.
Comments
Post a Comment