Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use indexers with Extension Methods having out parameter and function calls

Is it possible to use indexers with extension methods.

eg. Consider it as an example only.

    public static object SelectedValue(this DataGridView dgv, string ColumnName)
    {            
        return dgv.SelectedRows[0].Cells[ColumnName].Value;
    }

EDIT

  1. usage mygrid.SelectedValue("mycol")

  2. How to use it as an indexer mygrid.SelectedValue["mycol"] rather than above one.

  3. Is it possible to use it like this as well ? mygrid.SelectedValue["mycol"](out somevalue);

What are the syntax of getting this kind of values. Any simple example or link will work.

like image 569
Shantanu Gupta Avatar asked Jun 25 '10 10:06

Shantanu Gupta


People also ask

How do you implement and call a custom extension method?

To define and call the extension methodDefine a static class to contain the extension method. The class must be visible to client code. For more information about accessibility rules, see Access Modifiers. Implement the extension method as a static method with at least the same visibility as the containing class.

Can extension methods access private methods?

Extension methods can also access private static members of their static utility class. Even though this is tagged as C#, this applies to any of the . NET languages which provide support for extension methods.

Is it possible to achieve method extension using interface?

You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called. At compile time, extension methods always have lower priority than instance methods defined in the type itself.

How to call a method in Main in c#?

Calling a method is like accessing a field. After the object name (if you're calling an instance method) or the type name (if you're calling a static method), add a period, the name of the method, and parentheses. Arguments are listed within the parentheses and are separated by commas.


1 Answers

Well, there are two issues here:

  • C# doesn't (by and large) support named indexers1
  • C# doesn't support extension properties, so you can't make SelectedValue a property returning something indexable instead

So no, the syntax you've specified there won't work. You could get this to work:

mygrid.SelectedValue()["mycol"]

but that's a bit ugly. I'd stick with the method form if I were you.


1 C# 4 supports calling named indexers on COM objects.

like image 196
Jon Skeet Avatar answered Oct 25 '22 11:10

Jon Skeet