Operators in .NET

stovellp

Member
Joined
Mar 25, 2004
Messages
10
Ok this is an easy one.

How do I create a custom assignment operator for my own classes in C#? The types to be assigned to my class are DataReader classes (for SQL and Access) so my class may act as a wrapper for them.

Something like
Code:
class Myclass
{
  operator = (accessdatareader adr)
  {
    mydatareader = adr;
  }
}
 
In C# the assignment operator (=) cannot be overloaded. What are you trying to do? Is your class encapsulating the DataReaders and adding extra functionality?
 
Yep. I want to be able to do:

MyResultType result = sqlDataReader;

or

result = oledbDataReader;

or result = myresulttype;
 
Because I have a wrapper to make it easier to use the Data Adapters, and I also want to extend it into XML, my own config files, MySQL and other data sources, so if I used IDataAdapter I would be more limited.
 
Lol, currently Im just using functions such as AssignMSSQL(sqlDataAdapter);, Ill just keep it like that.

Is there a reason why the C# creators chose not to allow assignment overloading? I absolutely love C#, it kicked C++ off my favorite language shelf after only a month of using it, so Im sure they have a valid reason for doing this :)
 
I dont know why they cant but...
For your problem... maybe you could use a property to get the result ?
No ? Dont have to overload the assignement operator and got the job done.
 
Last edited by a moderator:
You can overload assignment though its syntax isnt quite the same - you dont overload the "=" operator.

Heres a sample for how to do it:
C#:
public static implicit operator MyResultType(DataReader op)
{
	return new MyResultType(op);
}

This allows assigning a variable of tyep MyResultType to a variable of type DataReader. In my sample, I assume you have a constructor on
MyResultType that takes a DataReader and does something useful with it.

You can replace implicit with explicit if you need to. Check the help on more info.

-Nerseus
 
Back
Top