473,595 Members | 2,474 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

2 questions about the extension methods in C# 3.0


Have just read about LINQ ant the new planned features of C# 3.0.
I think it's fantastic, but I have a few questions about extension
methods:
Question 1: Syntax
------------------
Why is the syntax for an extension method like this:

public int ExtMethod(this MyType t, int i, double d) { // t is this
t.I = i;
t.D = d;
}

instead of

public int ExtMethod(MyTyp e this, int i, int j) { // this is this
this.I = i;
this.D = d;
// or just:
I = i;
D = d;
}

? Then the body of an extension method would have the same
"pattern" as an ordinary instance method, which of course would
be ab advantage. So why didn't MS do it that way?
Question 2: Extending to interfaces?
------------------------------------
I realize that the primary purpose of extension method is LINQ, but
if you could also extend types "into interfaces", life would be much
easier also in other situations. Assume the following interface and
class:

public interface ICirkle {
public double R {get; set;}

}
public class Cirkle: ICirkle {...};

Now assume that someone adds this interface and this class:

public interface IEllipse {
public double R1 {get; set;}
public double R2 {get; set;}
}
public class Ellipse: IEllipse {...};

We then also want to be able to treat a cirkle like an ellipse. This
could hyphotetically be done by Cirkle being able to be "extended
into" IEllipse, with e.g. this syntax:

public static class ExtendCirkleInt oIEllipse: Cirkle =IEllipse {
public double R1 {
get {
return R;
}
set {
R = value;
}
}
public double R2 {
get {
return R;
}
set {
R = value;
}
}
}

This would mean that in every piece of code where ellipses are
handled, cirkles could be treated as ellipses. Kind of "backward
inheritance".

This is actually a very common situation, and it kind of "puts
oo on it's head": The common case (e.g. cirkle) is the simple
case, and the more general case is the complex and less usual.
I.e. what's logically a "subclass" needs _less_ data than the
base class.

So, does MS have any ideas in that direction?

/Samuel

Oct 27 '06 #1
2 1653
Samuel,
>? Then the body of an extension method would have the same
"pattern" as an ordinary instance method, which of course would
be ab advantage. So why didn't MS do it that way?
I don't know for sure why, but I like the current syntax better than
yours. Extension methods must be static, and up to now the this
keyword couldn't be used in static methods bodies. Your suggestion
would need to change that.

Also, just typing

I = i;

could be ambiguous if there was a static field or property named I in
the extension method class and also an instance field or property
named I in the extended class.
Regarding your second queston. Why not just implement IEllipse
directly in the Circle class? Or if you don't control the Circle
class, write a simple adapter class implementing IEllipse and
delegating to ICircle.
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Oct 27 '06 #2
In article <uS************ **@TK2MSFTNGP02 .phx.gbl>,
ma************* *******@mvps.or g (Mattias Sjögren) writes:
Regarding your second queston. Why not just implement IEllipse
directly in the Circle class? Or if you don't control the Circle
class, write a simple adapter class implementing IEllipse and
delegating to ICircle.
Ok, I'll giv another example:

Suppose this pattern:
struct DateValuePair {
Date date;
double value;
}

public interface IMyValues {
public double getValue(Date date);
}

public class MyValues: IMyValues {
private InterpolationMe thod method;
private DateValuePair[] points;

public double getValue(Date date) {...}
}

Normally, you'd call it this way:

value = x.getValue(date );

However, assume that we from time to time have a simlple case where the
"MyValues" is just represented as double, i.e. the date-value structure
is "flat", e.g. a flat yield curve of interest rates.

In that case, we would like the double to behave as an IMyValue, i.e.
to return itself when the IMyValues.getVa lue is invoked on it, i.e.
x.getValue(date ) returns x when x is a double.

Now when I'm writing this, though, I realize that this might also
work if there is an implicit cast from double to an IMyValues, e.g.

public class DoubleMyValues: IMyValues {
private double value;
public DoubleMyValues( double value) {this.value = value;}
public static implicit operator DoubleMyValues( double value) {
return new DoubleMyValues( value);
}
public double getValue(Date date) {return this.value;}
}

I'm relatively new to this kind oc casting in C#, so I'm not sure
it would work in all situations. In the test program i wrote i did
NOT work, there was no conversion from double to DoubleMyValues.
(Isn't implicit casting supposed to do just that??)

/Samuel

Oct 28 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1613
by: Collin Winter | last post by:
While working on a test suite for unittest these past few weeks, I've run across some behaviours that, while not obviously wrong, don't strike me as quite right, either. Submitted for your consideration: 1) TestCase.tearDown() is only run if TestCase.setUp() succeeded. It seems to me that tearDown() should always be run, regardless of any failures in setUp() or the test method itself. The case I'm considering is something like this,...
3
1642
by: Deckarep | last post by:
I recently got into somewhat of a debate with a fellow co-worker. First I asked him if he new of a way to add a method to an existing class like enhancing a class but without using Inheritance. He asked, "Why on earth would you want to do this? Just inherit." I told him other dynamic languages can do this such as JavaScript where you can just add method to say the Array classes prototype chain. I told him I found this technique often...
1
2410
by: gregory.lielens | last post by:
Hello, We are currently writing python bindings to an existing C++ library, and we encountered a problem that some of you may have solved (or that has found unsolvable :( ): A C++ class (let's call it CClass) is binded using classical Python extension API to _PClass, which is accesible through python without any
8
1769
by: Steven Nagy | last post by:
Some simple yes/no questions. I tried googling first and couldn't find specific answers. These are related to .Net 3.5 extension methods 1) I found that I would like to add properties as well as methods. Is there such a thing as Extension Properties? 2) Can you add static extension methods to classes? The 'this' part implies an instance. For example, I'd like to be able to go: System.IO.File.MyCrazyMethod()
4
3353
by: Steffen Bobek | last post by:
Extension methods are made for use with instances. I'd like to "misuse" them as static methods, too. Let me tell you my ambition: I use an extension method to serialize objects somehow like this: MyObject obj = new MyObject(); obj.ToXmlFile("some directory\\some file.xml"); The method "ToXmlFile" is defined elsewhere far apart from MyObject to work for all objects:
3
2093
by: raylopez99 | last post by:
The headline says it all. Great minds think alike: read the blog below from three years ago, as endorsed by Ritchie, who coinvented C. BTW the below lambda expression code will not work (.Where not recognized). I am using the 'standard' using directives using System;using System.Collections.Generic;using System.Diagnostics;using System.Text; And Visual Studio 2007.
4
3301
by: Rene | last post by:
Hi, I was wondering if anyone could tell me why extension methods must be declared on static classes. I mean, why not allowing them to be declared as static methods in regular instance classes? In case you are wondering, I am only curious to find out the reason for this limitation. I don't really have a need to declare extension method on non static classes. I am just curious.
1
1693
by: Simon Woods | last post by:
Hi I have 2 classes which are both instantiated by shared factory methods and both implement a common interface. Public Class Factory Public Shared Function CreateMyClass1() As MyClass1 Return New MyClass1 End Function
3
4827
by: johanatan | last post by:
When I first heard about these new features, I was very excited as it would have (if implemented as I had expected) rendered mimicking multiple inheritance almost painless in C#. Unfortunately, due to a couple limitations of the language, MI is still not attainable (at least not succinctly). 1 - Interfaces cannot define data (only properties) 2 - Extension methods cannot be used to mix in property definitions (or implement interface...
0
8261
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8379
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8019
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6674
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5839
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5418
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3873
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2391
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1223
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.