How to Overload the [] Operator in C#

How do I overload the [] operator in C#

public int this[int key]
{
get => GetValue(key);
set => SetValue(key, value);
}

Overload [] operator in C# and give more than one return value

In c# these are called indexers.

Syntax:

public object this[int key]
{
get
{
return GetValue(key);
}
set
{
SetValue(key,value);
}
}

You can return only one object. Use a base class instead for all the type objects you have to return.

Can I overload the = assignment operator?

You can make implicit conversion in other direction string -> CharArray:

public static implicit operator CharArray(string s)
{
return new CharArray(s.Length){ Value = s };
}

Then this works:

CharArray field = new CharArray(10);
field = "Test"; // all good!
string fieldAsString = field;

operator Overloading in C#

  1. Yes. Because you aren't dealing with instances always with the operators.
  2. Just change the types to what you want.

Here is an example for #2

public static Point operator+(int value, Point point2)
{
// logic here.
}

You will have to do the other way with the parameters if you want P2 + 2 to work.

See http://msdn.microsoft.com/en-us/library/8edha89s.aspx for more information.

How can I overload the [] operators?

I'm pretty sure this is what you're after:

public TValue this[TKey key] {
get { return _dictionary[key]; }
}

If you want to implement an interface to indicate to client code that your class can be accessed by an index of type TKey, the closest match (that I'm aware of) is IDictionary<TKey, TValue>.

Unfortunately, IDictionary<TKey, TValue> has a whole bunch of members that violate your read-only requirement, which means you would have to explicitly implement lots of members only to throw a NotImplementedException (or somesuch) when they're called: namely, the setter for this, Add, Clear, and Remove.

Maybe there's a different interface that would be more appropriate for this purpose (something like IReadOnlyDictionary<TKey, TValue>?); I just haven't come across it.

You could also write your own interface, of course, if you intend to have multiple classes that offer functionality similar to this.

How do I overload the square-bracket operator in C#?

you can find how to do it here.
In short it is:

public object this[int i]
{
get { return InnerList[i]; }
set { InnerList[i] = value; }
}

If you only need a getter the syntax in answer below can be used as well (starting from C# 6).

Overloading assignment operator in C#

It sounds like you should be using a struct rather than a class... and then creating an implicit conversion operator, as well as various operators for addition etc.

Here's some sample code:

public struct Velocity
{
private readonly double value;

public Velocity(double value)
{
this.value = value;
}

public static implicit operator Velocity(double value)
{
return new Velocity(value);
}

public static Velocity operator +(Velocity first, Velocity second)
{
return new Velocity(first.value + second.value);
}

public static Velocity operator -(Velocity first, Velocity second)
{
return new Velocity(first.value - second.value);
}

// TODO: Overload == and !=, implement IEquatable<T>, override
// Equals(object), GetHashCode and ToStrin
}

class Test
{
static void Main()
{
Velocity ms = 0;
ms = 17.4;
// The statement below will perform a conversion of 9.8 to Velocity,
// then call +(Velocity, Velocity)
ms += 9.8;
}
}

(As a side-note... I don't see how this really represents a velocity, as surely that needs a direction as well as a magnitude.)

How to overload Null-conditional operators ?.

No, you can't overload the Null-conditional operators. See the list of C# Overloadable operators.


Addendum The ability to overload this operator has actually been proposed to the C# language team. See Proposal: Allow null conditional (?.) and null coalescing ()?? operators to be overloaded and Proposal: nullable-like types. These has not been aproved.

What follows is my understanding of the concerns regarding these and similar proposals:

Changing the semantics of these operators could have a lot of ramifications. For example, given that the operators are static, it would be possible to make it say that something that is null is not. Which would mean a lot of problems for a lot of code. On the flip side, you could have code that hangs too long on a reference or not long enough that would bring problems with the garbage collection.

Even if these and similar issues could be solved, it is not a change to be taken lightly. We are talking about a lot of problems for existing code, that is already deployed in production.

C# - Operator Overload Extensions

Three options:

  1. Subclass them, and write overloads for the subclass
  2. Use Microsoft's publicly available source code for the respective classes (or decompile them), and write your overloads. This is not maintainable in the long term, or necessarily easy, but it will work.
  3. Stick with your extension methods.
  4. Conversion operators between your class and a "clone" class as described below.

In the comments, the OP has specifically mentioned using System.Drawing.PointF. What I've done in the past, with sealed classes like this, is to develop a second similar class using the .NET source as described above. Let's call this second class MyCustomPointF. I can write operators for my new class. But what I'm also going to add is what's called an implicit conversion operator that helps the compiler to convert an instance of my class back to a System.Drawing.PointF instance when I need it (without calling an external conversion function). It's not perfect, but it's an option.

Is it possible to do operator overloading with ListT without inheriting from it?

you can not do operator overload outside the class. you can use container for operator overloading

you can run this code hereurl


using System;
using System.Collections;
using System.Collections.Generic;

public class Program
{
public static void Main()
{
Run();
}

public static void Run()
{
var ls = new List<int>(){
1,3,5,7,9,11
};
var ls2 = new List<int>(){
2,4,6,8,10
};

var lsContainer = new AdditionContainer<List<int>,int>(ls);
var ls2Container = new AdditionContainer<List<int>,int>(ls2);
var finalAnsower = lsContainer +ls2Container;
finalAnsower.List.ForEach(f=>Console.WriteLine(f) );

}

}

public class AdditionContainer<TList,T>

where TList:List<T>
{
public TList List;
public AdditionContainer(TList list )
{
List=list;
}

public static AdditionContainer<TList,T> operator +(AdditionContainer<TList,T> a, AdditionContainer<TList,T> b)
{
b.List.ForEach(l =>{
if(!a.List.Contains(l))
{
a.List.Add(l);
}
});
return a;
}
}


Related Topics



Leave a reply



Submit