Domanda

Well i just discovered extension methods, Extension methods allow extending methods and functionality to an existing type without needing to change the code : Here

// Extending using Extension methods
static class MyExtensionMethods
{
    public static int Negate(this int value)
    {
        return -value;
    }
}

static void Main(string[] args)
{
    //Using extension method
    int i2 = 53;
    Console.WriteLine(i.Negate());
}

My Question :

Is it possible to do the same thing with object, like for example add the int Id to Form, so i can do like :

Form frm = new Form();

frm.Id = 2;
È stato utile?

Soluzione

Yes, you can create extension methods on any type of class you want.

However, your example is not a method but a property and you cannot create extension properties.

The following is valid:

static class FormExtensions{

    public static void SetId(this Form form, int someId)
    {
        // Do something with someId here
    }
}

// Call it like this:
Form frm = new Form();
frm.SetId(2);

Altri suggerimenti

Form is just another object in C#... a string may be immutable, but it's just another object so there is no reason you can't create extension methods for Form.

You cannot, however, add property setters and getters like in your example. Eric Lippert talks about this on his blog.

Extension methods are not extension properties. The method looks like it is part of the object, but in reality it is static method operating with the object. Your first example is converted by compiler to:

MyExtensionMethods.Negate(i)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top