C# mimic overridding the assignment operator (=) - c#

I've got a bit of a problem with a somewhat simple wrapper class I have.
It looks something like this:
public class Wrapper<T>
{
private T _value;
public Wrapper<T>(T value)
{
_value = value;
}
public static implicit operator Wrapper<T>(T value)
{
return new Wrapper<T>(value);
}
public static implicit operator T(Wrapper<T> value)
{
return value._value;
}
}
I've overriden the implicit converters from and to T, so it behaves almost like an instance of T itself.
e.g.
Wrapper<int> foo = 42;
However I've got a slight problem when assigning one instance of Wrapper to another, since I only want to assign the value of the second Wrapper class.
So right now, I have to do this:
Wrapper<int> foo = 42;
Wrapper<int> bar = (int)foo;
Or expose _value publicly through a property.
However since this is in a library, and I don't want the user to depend on remembering this, do you guys have any idea how I could mimic overridding the assignment operator ?
The problem in just changing the pointer (as it does when assigning a class instance to another), is that I've got a dictionary of pointers to these Wrapper objects, so I cannot have them changing all the time, since the dictionary would stop matching then.
I can see if this is somewhat confusing, so if I've left anything important out, please feel free to ask :-)

Since the assignment operator can't be overloaded, there isn't a real good solution. As somebody else pointed out, using a struct will give you the assignment semantics that you want, but then you're faced with value semantics--often not a good thing.
One option is to overload the constructor:
public Wrapper(Wrapper<T> w)
{
_value = w._value;
}
Which would result in this syntax:
Wrapper<int> foo = 42;
Wrapper<int> bar = new Wrapper<int>(foo);
Although more verbose than what you have, it reads better.
Or you could add a Clone method (not the ICloneable interface), so that you could write:
Wrapper<int> bar = foo.Clone();
You could get really creative and overload some operator, making it do essentially nothing. I wouldn't recommend that, though. Using operator overloading for those kinds of things typically makes code cryptic and often breaks.

You could make Wrapper<T> a struct. However I'm not sure if this would suit your application design or not.

If you look at Nullable<T>...which does a very similar thing to what you are doing here, it exposes the internal value using a .Value property.
The problem in just changing the pointer (as it does when assigning a class instance to another), is that I've got a dictionary of pointers to these Wrapper objects, so I cannot have them changing all the time, since the dictionary would stop matching then.
I'm not sure I follow this, what exactly are you storing in the dictionary? Because if you are storing references, the CLR will update them as necessary.

Don't implicitly cast your wrapper both ways.
public class DBValue<T>
{
public static implicit operator DBValue <T>(T value)
{
return new DBValue<T>(value);
}
public static explicit operator T(DBValue <T> dbValue)
{
return dbValue.Value;
}
private readonly T _value;
public T Value { get { this._value; } }
public DBValue(T value)
{
this._value = value;
}
}
Casting from DBValue<T> to T is a lossy conversion (as a minimum, you lose the fact that it's a value from the database), and by best-practice should be explicit. If you don't lose anything by casting from DBValue<T> to T, you might as well just use properties that return T.
Basically, you've already seen why you shouldn't be trying to do this: if a DBValue can be substituted for T and the other way around, how does the compiler (or developer) know which one to choose?
Requiring down-stream developers to write:
string value = MyProperty.Value
or
string value = (string)MyProperty
instead of
string value = MyProperty
...isn't all that onerous, and makes sure that everyone knows exactly what's going on.
EDIT:
To actually answer the question, you can't override reference assignment - or make it look like you have - but you shouldn't really need to.

This is what properties are for. They allow you to define what assignment means. You can't define it for a class or struct itself because they are already defined by the language to do necessary things. Just add a Value property to the class.
Alternatively, edit your question to give a broader description of your design and how this Wrapper fits into it, as someone may be able to suggest a simpler approach.

I just looked into it, making the class a struct is really not an option, since it has some logic in the parameterless constructor, plus it inherits an abstract class, which contains internal abstract functions.
I cannot use an interface, as that'd make those functions public, which would break the logic entirely.
I can post the entire class if that'd be helpful, but it's somewhat long (130 lines)
Or I could toss up on a seperate server, if that'd be better ? (though it hurts the integrity of this question, as I may delete it eventually from that server)
Also explaining the class is really difficult, without writing a complete essay :-/
Anyway I'll try to illustrate the problem I'm having.
Assume 2 table classes: CustomerTable and UserTable:
public class CustomerTable
{
Wrapper<string> Name;
}
public class UserTable
{
Wrapper<string> Name;
}
Now the problem is that some other developer, may use the above code as follows:
CustomerTable customer = new CustomerTable();
UserTable user = new UserTable();
user.Name = customer.Name; // This breaks my internal dictionary
What the developer should had done, in order for it to work, was:
user.Name = (string)customer.Name;
The problem is however, who in their right mind would think about that, when writing code ?
Even if I used a Value property, the developer would still have to remember to write
user.Name = customer.Name.Value; // or user.Name.Value = ....
And again the developer may forget this, and all of a sudden he gets exceptions, or worse: data which isn't persisted to the database.
So my issue is really, that I want the wrapper to be completely transparent (it should be usable as if it was in fact the class/primitive it's wrapping).
However when assigning from one wrapper to another, my internal logic breaks.
Phew a lot of writing, and a lot of code - let me know if I overdo the writing.

A J Lane I see what you mean, and I guess you're right - I just wanted to make it as simple as possible to use the library.
The reason for the implicit cast from DbValue to T, is to simply functions which expects T.
for example
literalSomething.Text = Server.HtmlEncode(SomeTable.SomeStringColumn);
rather than
literalSomething.Text = Server.HtmlEncode((string)SomeTable.SomeStringColumn);
This requires the cast to be implicit.
That being said I just read your comment whilst typing this, and I can see that's quite the issue.
I think I'll go back to exposing value through a property, it just requires the developer to type more, and kinda makes the code ugly I think.
Just imagine DbValue:
if (someValue.Value.HasValue) // someValue is DbValue<int?>
But then again it's probably better with "ugly" code, than code which behaves differently from what you'd expect by merely reading it.
I guess this question ends up as a "best practice" question really.
So to conclude, I'll create a Value property and use that instead of implicit casts, and the developer using the library will just have to live with that.
Thanks for your inputs :-)

This old post stills needs additional information to be complete. It's apparent that the original desired behavior cannot be accomplished since the = operator cannot be overloaded, and likewise C# cannot be "tricked" into casting an object to its own type... it will always boil down to a class reference assignment. But Steffen's further posts show the Wrapper class being used not just with local variables, but as a class field type. The desired semantics can be used AND the integrity of the internal dictionary maintained by using class properties instead of public fields.
Even keeping the original given Wrapper<T> class with both its implicit operators, here's code that would work:
public class CustomerTable
{
private Wrapper<string> _Name;
public Wrapper<string> Name {
get { return _Name; }
set { _Name = (string)value; }
}
}
public class UserTable
{
private Wrapper<string> _Name;
public Wrapper<string> Name {
get { return _Name; }
set { _Name = (string)value; }
}
}
If this change were made, it would not break existing code since it still allows various modes of setting the property:
CustomerTable customer = new CustomerTable();
UserTable user = new UserTable();
user.Name = customer.Name; //*** No longer breaks internal data structures
user.Name = "string literal"; // Works as expected with implicit cast operator
user.Name = (string)customer.Name; // Still allowed with explicit/implicit cast operator
user.Name = customer.Name.Value; // Also works if Value property is still defined
Because this still doesn't answer the original question, use of the Wrapper class could still be problematic if its used outside the class property context, i.e. passed between object, etc. Perhaps the entire Wrapper class could be eliminated with the proper class design, including use of property set/get accessors.

Related

Casting to arbitrary non-generic return type at runtime, C#

I'm trying to make a user-friendly debug framework where users can create more debug variables as easily as possible.
I need to cast an object to the return type of my property/method (bool, int, whatever), without knowing what that return type is.
tldr: How can I return a non-generic type (in this example bool) from
public bool MyGetSetProperty {
get {
object obj = new object();
return (bool)obj;
}
}
WITHOUT specifying "return (bool)"? So something like
return (GenericThingHereThatPassesAsBool)obj;
or
return obj as MyGetSetPropertyReturnType;
----------
Detail:
I want users to be able to create new properties in this class as easily as possible - basically copying+pasting the whole code block below, and only replacing "SerializeAll" with their variable name, and the type declaration "bool" with the type they want on the field/property declarations.
In my getter, I have a couple separate checks to see if the entire debug system is enabled. If not, it returns a default value for the given variable.
[Tooltip ("Serialize ALL XML output fields?"), SerializeField]
private bool debugSerializeAll = false;
/// <summary>
/// Serialize ALL XML output fields?
/// </summary>
[DebugValue, DebugDefault (true)]
public bool SerializeAll {
get {
if (!classEnabled || !debug.debugEnabled)
return (bool)GetDefaultValue (MethodBase.GetCurrentMethod ());
return debugSerializeAll;
}
set { debugSerializeAll = value; }
}
The thing is, I can't return "default" because the default value can be overridden - see the "DebugDefault" attribute where the "default" value for this bool is actually "true", at least as far as my debug system is concerned. The method "GetDefaultValue" accommodates for that, and it returns an object that could be a string, int, bool, anything.
I'm already doing funky reflection stuff to access the MethodInfo, PropertyInfo, etc of the getter and property SerializeAll. I just can't figure out how to not have to also specify the (bool) cast on the return. Again, the goal is as little human editing as possible.
Thank you!
You should be able to do this with a cast to dynamic.
return (dynamic)GetDefaultValue (MethodBase.GetCurrentMethod ());
Bear in mind that the compiler isn't actually making this into a cast to bool. Rather, this makes the compiler ignore compile-time type-safety, and instead the program will use reflection at runtime to figure out the best way to take the value returned from GetDefaultValue and turn it into what it needs to be.
I want users to be able to create new properties in this class as easily as possible...
This is a good principle.
... basically copying+pasting the whole code block below, and only replacing "SerializeAll" with their variable name, and the type declaration "bool" with the type they want on the field/property declarations.
That totally breaks the principle you just mentioned, and results in a bunch of boilerplate code and other code smells.
In theory, you could probably create a Fody Weaver or something to add this boilerplate code upon compilation. But that's probably more work than it's worth.
I would hazard a guess that this is an "XY Problem", where you're asking how to achieve the solution that you've imagined, rather than asking how to solve the problem you're actually facing.
Why should every property in your class return a completely different value if certain private fields are set a certain way? This sounds like a big Separation of Concerns problem, where you're tasking your class with doing two completely different things. I strongly suggest you find another way to solve the problem you're trying to solve. For example, when code tries to get an instance of your class, it could go through a method that checks the classEnabled and debug.debugEnabled concepts (which probably belong in a different class), and returns an instance with the properties all set to their defaults.
Please Link click here -> How to cast Object to boolean?
or
I think you need to study for Generic class
Check if a class is derived from a generic class

Cast Boxed Object back to Original Type

I expect there's one of two answers to this, either impossible or extremely simple and I've overlooked the obvious Google query.
The underlying issue is that I have a generic object being passed in via an EventHandler that boxes the object and obfuscates the true type; only at runtime do I know what the object is.
Admittedly the dynamic keyword can get around the issue, but I'd like to not lose IntelliSense and everything if I can avoid it. Plus, it doesn't solve not knowing what each of the properties of the generic object are without massive amounts of reflection.
EDIT: The idea is to be able to determine the true type of the an object in a method parameter, and then cast that object as it's true type without knowing it in advance. This is but a simplified example. Boxed may have been the wrong term.
An example:
public class Program
{
static void Main(string[] args)
{
var container = new Container<Containee>(
new Containee
{
Property1 = Guid.NewGuid(),
Property2 = "I'm a property!",
Property3 = DateTime.Now
}
);
var boxed = (object)container;
var originalType = boxed.GetType();
// DOES NOT COMPILE: would like an operation like this
// EDIT: Request for more detail
var actualType = boxed as originalType;
actualType.Entity.Property2 = "But I like this better.";
}
}
public class Containee
{
public Guid Property1 { get; set; }
public string Property2 { get; set; }
public DateTime Property3 { get; set; }
}
public class Container<T>
{
public Container(T entity)
{
Entity = entity;
}
public T Entity { get; internal set; }
}
Clearly that won't compile, as there's not really a way to cast as a variable. However, I'm hoping there's a way to get a reference to the actual object and type, or at least, a way to dynamically re-create the type.
I expect there's something simple I'm overlooking, or a better way to get around it in general. The point is to be able to wrap any object in the container, and figure out later what it was.
The idea is to be able to determine the true type of the an object in a method parameter
That's easy enough (and you're already doing it).
Type actualType = param.GetType();
That will get you the actual concrete type of the object
and then cast that object as it's true type
This is where things come off the rails a bit. The casting operator in C# (usage of which is what people refer to as "casting") can do two things:
Use type-specific explicit conversions to create a new object by applying the conversion to the existing object (note that this is a new reference that is created; the original object's type is never changed)
Allow the developer to reference an object as a type that is at a different level in its inheritance hierarchy than is currently provided (or an interface that is implemented on a type that is lower in the hierarchy than is currently referenced)
In your case, the first option is right out; the casting operator, like all operators, is not polymorphic. That is, an operator is only applied if it is defined on the type that is being referenced, not the object that's being referenced. If you'd like further clarification on this, let me know, but I don't think it's germane to your question so I'm not going to go into it further unless asked.
The second option is the only option that could realistically apply to you, but consider the only two reasons you would want to do this:
So that you can refer to the object as a specific concrete type that is at a lower level than is currently provided (in your case, your object is an object, so that's pretty much as high as it goes)
So that you can refer to an object as a type that is higher in the hierarchy so that you can bypass hidden (but not overridden) members.
(The vast majority of casts are for reason #1)
The reason you would want to use either of those options is so that you can have a strongly-typed object and use the various members defined on that type. But all of these things only apply to types that you know when you're writing the code. It doesn't make sense to cast to a type that is unknown at compile time, as casting doesn't do anything to the actual object (it is, and shall remain, its true type; the only thing that changes is the type of the variable by which you reference the object).
If you can provide a further fleshed-out example of what you're actually trying to do (complete with code as you'd either like or expect it to work), I might be able to provide something modeled a little closer to what you want, but as it's described this is as specific as I can get.
First of all: That's not "boxing". Boxing is for value types, like structs.
Second of all: What you probably need is either:
Compile-time reflection, which C# doesn't have
Dynamic code generation, which you can do (painfully) with Reflection.Emit.
Third of all: Your sample code does variable1 as variable2, which doesn't really make sense. :\ What are you intending to do after that? Perhaps there's a better way.
You could use dynamic:
dynamic actualType = boxed;
actualType.Entity.Property2 = "But I like this better.";
This should compile and work.
var actualType = boxed as originalType;
Just so we're on the same page, let me explain why this is impossible.
var is a compile time construct. It is, identical to declaring the variable with the proper type straight off. Besides being easier to type, it's main use is for anonymous types which, as implied, have no names.
Anyway, to get to the meat of your question, your best bet is to use Dynamic code generation, either with Reflection.Emit or CodeDom (the latter is much easier to understand if you don't know ILASM, but is much slower).
Depending on what you actually want to do, you might be able to get away with something like
if(someObject is Container<Containee>) {
var container = (Container<Containee>)someObject;
//...
}
But, if you can expect literally any type, well... good luck.
The underlying issue is that I have a
generic object being passed in via an
EventHandler that boxes the object and
obfuscates the true type; only at
runtime do I know what the object is.
How do you want to handle it, if the type is only known at runtime? You can't call any specific class methods because you won't know the exact type anyway, unless all objects share some set of methods which can be extracted as interface.
Basically, you have several options:
Use is and do different things for different types:
object value = GetValue ();
if (value is Program)
((Program)value).Run ();
else if (value is Animal)
((Animal)value).Run ();
If all possible types are supposed to share a set of operations, use an interface:
object value = GetValue ();
IRunnable runnable = (IRunnable)value;
runnable.Run ();
Rephrase your question and extend your sample with how you see it working after you've done the ‘magical casting’. This would give us the idea what you're trying to accomplish.

A List of varying types?

Id' like to create a list of data that will be passed from method to method, however I can't use a struct because the data that will be contained in this list will vary depending on the input.
For example
if (x == 1) {
a = 1
b = true
c = 42
d = "hello"
}
if (x == 2) {
a = 2
b = 'g'
c = "sup"
}
I believe my options are thus:
Create an array or List of strings, and cast the data back to what it originally was from strings. This is messy and could lead to bugs of uninterpretable input, though wouldn't be so bad since it'd all be detected at runtime.
Create a struct for each possibility - Is this even good practice?
Somehow use generics. From what I know, while generics are type-safe yet not type-strict, they must be cast to types before being used. Eg if I wanted a List of items here, I'd need to cast them to strings much like would happen with solution 1, making this useless.
My question then, is which of these options is the best? Or is there an alternate option using some sort of generic type I don't know about? The number of possible variables in each case may change, as with their types. I'd like to be able to return a single List or Array to the calling method, so that it may appropriately deal with the result. It will know how to deal with each group of data based on the value of a, as it will be the 'action choice' identifier. I'm also aware that casting them to objects and back each time is very intensive so I'd rather avoid that.
This is probably pretty simple but it has me stumped...
Since you don't know before hand what the list will contain, it looks like a good case for using an ArrayList.
If you want to get back to the values using a key, consider using a Hashtable.
The general principal in .NET is that every type can be cast to System.Object (although it may involve boxing). You can use a method like
void Foo(params object[] parameters) { ... }
Or use the System.Collections.ArrayList class.
The 'problem' is that when you want to use such a value, you will need code like:
if (parameters[i] is string)
{
string s = (string) parameters[i];
...
}
Sorry, this is not a code related answer: there may be a faulty design hidden behind such a construct. Make sure you know what you are doing, otherwise things might fire back.
If not knowing the type of the fields you use beforehand really is required, this calls for an approach that saves the data with their type, like
struct foo {
private object _value;
private string _type;
foo(string myType, object myValue) {
_value = myValue;
_type = myType;
}
}
and then using Generics to handle the business logic.
Basically you need a list typed to Object, and then yes, you're in a mode of casting back.
My question is, structurally, how will you know what indexes are of which type? This sounds like a painful solution at best.
If you really need to store differing types in the list, perhaps try a struct which contains a member of each type, as well as a flag indicating which data type is represented. Then use a generic collection for that struct. Something like (off the top of my head)
struct FooType
{
public string StringValue;
public bool BoolValue;
public int IntValue;
public char CharValue;
public string DataType;
// You'd probably want constructors too
}
Then the generic list:
var values = new List<FooType>();
Now you can add and remove entries in the list using that type, which would then indicate what the core data really is.
I still don't like the answer; it sounds like your design may be trying to do too much and there may be refactoring opportunities, but since I don't see much more of your code or intent, all I can do is answer what you've asked. :)
You could represent the data items using a Dictionary/Hashtable and then add these dictionaries to a List.
You could also add extra type information into the dictionary value if needed.

How to cast object to type described by Type class?

I have a object:
ExampleClass ex = new ExampleClass();
And:
Type TargetType
I would like to cast ex to type described by TargetType like this:
Object o = (TargetType) ex;
But when I do this I get:
The type or namespace name 't' could
not be found
So how to do this? Am I missing something obious here?
Update:
I would like to obtain something like this:
public CustomClass MyClassOuter
{
get
{
return (CustomClass) otherClass;
}
}
private otherClass;
And because I will have many properties like this I would like do this:
public CustomClass MyClassOuter
{
get
{
return (GetThisPropertyType()) otherClass;
}
}
private SomeOtherTypeClass otherClass;
Context:
Normally in my context in my class I need to create many properties. And in every one replace casting to the type of property. It does not seem to have sense to me (in my context) because I know what return type is and I would like to write some kind of code that will do the casting for me. Maybe it's case of generics, I don't know yet.
It's like I can assure in this property that I get the right object and in right type and am 100% able to cast it to the property type.
All I need to do this so that I do not need to specify in every one property that it has to "cast value to CustomClass", I would like to do something like "cast value to the same class as this property is".
For example:
class MYBaseClass
{
protected List<Object> MyInternalObjects;
}
class MyClass
{
public SpecialClass MyVeryOwnSpecialObject
{
get
{
return (SpecialClass) MyInteralObjects["MyVeryOwnSpecialObject"];
}
}
}
And ok - I can make many properties like this one above - but there is 2 problems:
1) I need to specify name of object on MyInternalObjects but it's the same like property name. This I solved with System.Reflection.MethodBase.GetCurrentMethod().Name.
2) In every property I need to cast object from MyInternalObjects to different types. In MyVeryOwnSpecialObject for example - to SpecialClass. It's always the same class as the property.
That's why I would like to do something like this:
class MYBaseClass
{
protected List<Object> MyInternalObjects;
}
class MyClass
{
public SpecialClass MyVeryOwnSpecialObject
{
get
{
return (GetPropertyType()) MyInteralObjects[System.Reflection.MethodBase.GetCurrentMethod().Name];
}
}
}
And now concerns: Ok, what for? Because further in my application I will have all benefits of safe types and so on (intellisense).
Second one: but now you will lost type safety in this place? No. Because I'm very sure that I have object of my type on a list.
Object o = (TargetType) ex;
This code is useless. You might have a type on the right but it's still only an object on the left side. You can't use functionality specific to TargetType like this.
This is how you can invoke a method of an unknown object of a given type:
object myObject = new UnknownType();
Type t = typeof(UnknownType); // myObject.GetType() would also work
MethodInfo sayHelloMethod = t.GetMethod("SayHello");
sayHelloMethod.Invoke(myObject, null);
With this UnknownType class:
class UnknownType
{
public void SayHello()
{
Console.WriteLine("Hello world.");
}
}
Usually a desire to do this indicates a misunderstanding. However, there are very occasionally legitimate reasons to do this. It depends on whether or not it's going to be a reference conversion vs an unboxing or user-defined conversion.
If it's a reference conversion, that means the actual value (the reference) will remain entirely unchanged. All the cast does is perform a check and then copy the value. That has no real use - you can perform the check using Type.IsAssignableFrom instead, and just use the implicit cast to object if you want it in a variable of type object.
The main point of casting is to provide the compiler with more information. Now if you only know the type at execution time, that clearly can't help the compiler.
What do you plan to do with o after you've performed the cast? If you can explain that, we can try to explain how to achieve the effect you're after.
If you really want a user-defined conversion or an unboxing conversion to occur, that could be a different matter - but I suspect that's not the case.
EDIT: Having seen your update, your property is just declared to return CustomClass, so all you need is:
public CustomClass MyClassOuter
{
get
{
return (CustomClass) otherClass;
}
}
I suspect you still haven't really given us all the information we need. Is that definitely how your property will be defined, with CustomClass being a definite type? Why were you trying to perform the cast dynamically when you know the property type?
EDIT: It sounds like you're just trying to save some typing - to make it easier to cut and paste. Don't. You know the type at compile-time, because you know the type of the property at compile-time (it's specified in the code just a few lines above). Use that type directly. Likewise don't try to get the name of the current method to work out the key to use. Just put the name in directly. Again, you know it at compile-time, so why be dynamic? I'm all for laziness when it makes sense, but in this case it just doesn't.
if (ex is ExampleClass)
{
ExampleClass myObject = (ExampleClass)ex;
}
That would do it but I guess the question is what are you trying to achieve and why? I often find that if something seems really, really difficult then I'm probably doing it wrong.
Now it seems to be impossible, but soon will be available with new feature in .NET 4.0 called "dynamic":
http://www.codeguru.com/vb/vbnet30/article.php/c15645__4/
I'm not entirely sure what you're trying to do, but the impression I'm getting is that you'd like to have a single instance of some object which can "act like" many different types of objects, and you want to have getters which will allow you to view this one object in those various different ways very easily. In that case, I would suggest making a single getter method (not a property), like so:
public T Get<T>()
{
return (T)myObject;
}
Then you would call it like so:
Foo foo = box.Get<Foo>();
Bar bar = box.Get<Bar>();
// etc...
Two things to note: this is definitely not type-safe, since you can pass any type for T, including types for which the cast will fail. You can constrain it a little, like so:
public T Get<T>() where T : SomeBaseType
Which will cause a compile error if you try to use a type which is incompatible with SomeBaseType, but I'm not sure that's totally robust. But hopefully this gets you most of the way there.
Is this what you had in mind?

Can a C# property accept multiple values?

This might be a bit of an anti-pattern, but it is possible for a property on a C# class to accept multiple values?
For example, say I have an Public int property and I always want it to return an int, but I would like to be able to have the property set by assigning a decimal, an integer or some other data type. So my question is if it possible for properties to accept multiple values?
I think what you mean to ask is: How does implicit and explicit casting work for int and decimal?
You are asking about implicit casting which automatically coverts one object to another defined type. You will not be able to do this for an int and decimal because they are already defined in the framework and you are not able to reduce the scope of the decimal by casting it to an int. But if you were using that as an example for actual objects that you created you can use the implicit link above, to learn more about how this works and how to implement it.
But you can always use the convert method to convert them to the right type;
public int MyProperty { get; set; }
...
obj.MyProperty = Convert.ToInt32(32.0M);
obj.MyProperty = Convert.ToInt32(40.222D);
obj.MyProperty = Convert.ToInt32("42");
Edit: This method can't be used since the op is specifically bound to properties.
I do not believe this is possible with the robustness that you describe. In this case you would likely be better off using an overloaded method (polymorphism).
This is what is typically known as a setter (or mutator) and you can overload the method to accept multiple different types of parameters. Each will perform differently if you wish. The way I have them set up might not be syntactically correct but that is the general idea you're looking for I believe.
public class MyClass {
private Int32 mySomeValue;
public void setSomeValue(Double value) { this.mySomeValue = Convert.ToInt32(value); }
public void setSomeValue(Int32 value) { this.mySomeValue = value; }
}
No. A property has a single value. You can assign anything to it that could be assigned to a variable of the same type.
It seems like you would have to ascertain the type at run-time. You could have the property accept an object, determine the type and take your action. You would have to throw exceptions for things you don't expect, of course. Like you say, probably not the best, but possible. :)
Properties are supposed to look sort of like public fields. Create setter-methods, or do the cast/conversion in the assignment statements as opposed to in the property-setter.

Categories

Resources