Overloading properties?

  • Thread starter Thread starter ORC
  • Start date Start date
O

ORC

Is it possible to overload properties - and if so - how?

Mayby there is another and better way to do what I'm trying to do so if you
have any suggestion I would be happy:

I have a number of properties to set and get values, but I want my
properties to be able to return a type that is corresponding to the target
variabel (and also be able to receive a type corresponding to the source)?

Thanks,
Ole
 
Is it possible to overload properties - and if so - how?
No


I have a number of properties to set and get values, but I want my
properties to be able to return a type that is corresponding to the target
variabel (and also be able to receive a type corresponding to the source)?

What if there is no target variable? Even if there is, there's no way
to know from inside a property getter.



Mattias
 
Hi,

Short answer: NO

to overload a method you need a different set of arguments, a different
return value cannot be used to overload, why? because it would be terribly
difficult, if not impossible to solve the correct instance of the method
when assigning to a variable of not the exact type declared in the method.

With that in mind AND remembering that the properties are methods in real
life is why you cannot do it.

Cheers,
 
Well, using an old trick I learned in C++, it can be done, sorta, but it's
still probably not a good idea:

public class A
{
private int _n;
public A(int n)
{
_n = n;
}
public AHelper TimesTwo
{
get
{
return new AHelper(this);
}
}
public int N
{
get { return _n; }
}
}

public class AHelper
{
private A _a;
public AHelper(A a)
{
_a = a;
}
public static implicit operator int(AHelper ah)
{
return ah._a.N *2;
}
public static implicit operator string (AHelper ah)
{
return String.Format("The value is {0}", ah._a.N *2);
}
}
public class MyClass
{
public static void Main()
{
A aa = new A(5);
int i = aa.TimesTwo;
string s = aa.TimesTwo;

Console.WriteLine("int ='{0}', string='{1}'", i, s);
}

}

--
Truth,
James Curran
[erstwhile VC++ MVP]
Home: www.noveltheory.com Work: www.njtheater.com
Blog: www.honestillusion.com Day Job: www.partsearch.com
 
You have to make your property use type "object" and sort it out
internally, I'm afraid.

It's not clear from your post, but maybe what you're more interested in
is generic types. Read up on "Whidbey", which is .NET Framework 2.0 and
all of the C# enhancements that come with it. Generics are one of the
heavy hitting changes.
 
Back
Top