The Scope of an Extension Method
As just explained, extension methods are essentially static methods that can be invoked from an
instance of the extended type. Given this flavor of syntactic sugar, it is really important to point out
that unlike a “normal” method, extension methods do not have direct access to the members of the
type they are extending; said another way,
extending is not inheriting. Consider the following simple
Car type:
public class Car
{
public int Speed;
public int SpeedUp()
{
return ++Speed;
}
}
If you were to build an extension method for the Car type named SlowDown(), you do not have
direct access to the members of Car within the scope of the extension method as we are not per-
forming an act of classical inheritance. Therefore, the following would result in a compiler error:
public static class CarExtensions
{
public static int SlowDown(this Car c)
{
Do'stlaringiz bilan baham: |