What is an example of "this" assignment in C#? - c#

Does anybody have useful example of this assignment inside a C# method? I have been asked for it once during job interview, and I am still interested in answer myself.

The other answers are incorrect when they say you cannot assign to 'this'. True, you can't for a class type, but you can for a struct type:
public struct MyValueType
{
public int Id;
public void Swap(ref MyValueType other)
{
MyValueType temp = this;
this = other;
other = temp;
}
}
At any point a struct can alter itself by assigning to 'this' like so.

using the this keyword ensures that only variables and methods scoped in the current type are accessed. This can be used when you have a naming conflict between a field/property and a local variable or method parameter.
Typically used in constructors:
private readonly IProvider provider;
public MyClass(IProvider provider)
{
this.provider = provider;
}
In this example we assign the parameter provider to the private field provider.

only correct place for this from syntax point of view, is Extension methods in C# 3.0 when you specify first parameter of method as foo(ftype this, ...). and then can use this extension for any instance of ftype. But is's just syntax and not real this ovveride operation.

if you're asked to assign something to this, there's quite a few examples. One that comes to mind is telling a control who his daddy is:
class frmMain
{
void InitializeComponents()
{
btnOK = new Button();
btnOK.Parent = this;
}
}

I know this question has long been answered and discussion has stopped, but here's a case I didn't see mentioned anywhere on the interwebs and thought it may be useful to share here.
I've used this to maintain immutability of members while still supporting serialization. Consider a struct defined like this:
public struct SampleStruct : IXmlSerializable
{
private readonly int _data;
public int Data { get { return _data; } }
public SampleStruct(int data)
{
_data = data;
}
#region IXmlSerializableMembers
public XmlSchema GetSchema() { return null; }
public void ReadXml(XmlReader reader)
{
this = new SampleStruct(int.Parse(reader.ReadString()));
}
public void WriteXml(XmlWriter writer
{
writer.WriteString(data.ToString());
}
#endregion
}
Since we're allowed to overwrite this, we can maintain the immutability of _data held within a single instance. This has the added benefit of when deserializing new values you're guaranteed a fresh instance, which is sometimes a nice guarantee!
}

You cannot overwrite "this". It points to the current object instance.

Related

Accessing to a property of a non-static class in any place

I come today with a weird question.
Is there a way where I can use a non static class like static?
I.e:
We have the following classes:
public class Parameters
{
public String LoadType { get; set; }
public Parameters (String inLoadType)
{
LoadType = inLoadType;
}
}
public class MainClass
{
public Parameters Parameters { get; set; }
public MainClass(String inLoadType)
{
Parameters = new Parameters(inLoadType);
}
}
Now we instantiate MainClass, then somewhere in another place that is not the MainClass I would like to access to the LoadType.
It should be threadSafe, also the operation take quite long, that is the reason I cannot simply just use a lock and make it static.
The class where I want to access that variable is static, I thought in a workaround with a static Event in the Parameters class, and whoever call the event would get the value of the instantiated class or something like that.
Any other Ideas about it beside passing as parameter to the static method what I need?
Sounds like stupid question but I just want to know if is possible or not.
Imagine, that you have two Parameters instances
Parameters one = new Parameters("One");
Parameters two = new Parameters("Two");
and then you call:
String result = SomeWeirdBlackMagicCallOfLoadType();
What is the expected result? "One" or "Two"? In order to solve this
problem, you can turn Parameters into singletone (one instance only) and thus the call will be
String result = Parameters.Instance.LoadType;
but I suggest treating static as static when data doesn't depend on instance. In case of long operations, thread safety you can use Lazy<String> which is specially designed for that:
public class Parameters {
private static Lazy<String> s_LoadType = new Lazy<string>(() => {
....
return "bla-bla-bla";
});
public static String LoadType {
get {
return s_LoadType.Value;
}
}
...
}

An object that securely provides both public API (read-only) and private API (read-write)

This is an architecture problem. Programmers encounter this encapsulation problem quite often, but I haven't yet seen a complete and clean solution.
Related questions:
readonly class design when a non-readonly class is already in place
Controlling read/write access to fields
Normally, in OOP paradigm, objects store their data in fields. The class' own methods have full access to its fields. When you need to return value, you just return a copy of the data, so that the outside code cannot break the data.
Now suppose that the data pieces are complex, so they're themselves encapsulated in class objects and that these objects cannot be easily copied. Now, if you return such object from some property, the outside code has the same access to it as your internal code. For example, if you return a List<int>, everyone can add values to it. This is usually undesirable.
This problem is usually worked around using read-only wrappers - you wrap your full-access internal objects in read-only wrappers before returning. The problem with this approach is that the wrapper may be a poor substitution for the wrapped value - the wrapper is a different class. (And if you derive the read-only wrapper from the modifiable class (or vise-versa), then anybody can up-cast/down-cast the "read-only" object to the modifiable object, breaking the protection.)
I want a pattern such that:
The data (say, an int value) has "public/read-only API" and "private/modifiable API".
Only the object creator has access to the "private/modifiable API".
The private/public APIs may have both passive parts (e.g. methods, properties) and active parts (e.g. events).
Delegates should not be used except at the object creation stage. All calls should be direct.
The access to the internal data from the "public/read-only API" (and, preferably, from the "private/modifiable API" too) should be as direct as possible. I don't want a big stack of wrappers to accumulate when composing such objects.
Here are the sample interfaces:
interface IPublicApi {
int GetValue();
}
interface IPrivateApi {
void SetValue(int value);
}
interface IPrivateConsumer {
void OnValueChanged(); //Callback
}
I have devised such scheme. I want you to critique my solution or give your own solution.
There are several sub-problems that have to be solved.
How to allow the "private API" code to access the private data without allowing the outside code to call it?
How to give the "private API" access to the object creator?
How to establish the two-way communication between the object and the code using the private API (calling/getting called)?
My system consists of these classes:
ReadableInt is the public API
ReadableInt.PrivateApi is the raw private API proxy object
ReadableInt.IPrivateConsumer is the public-to-private callback interface
public sealed class ReadableInt {
int _value;
IPrivateConsumer _privateConsumer;
public ReadableInt(IPrivateConsumer privateConsumer, Action<PrivateApi> privateConsumerInitializer) {
_privateConsumer = privateConsumer;
var proxy = new PrivateApi(this);
privateConsumerInitializer(proxy);
}
public int GetValue() {
return _value;
}
private void SetValue(int value) {
_value = value;
_privateConsumer.OnValueChanged();
}
public interface IPrivateConsumer {
void OnValueChanged();
}
public class PrivateApi {
ReadableInt _readableInt;
internal PrivateApi(ReadableInt publicApi) {
_readableInt = publicApi;
}
public void SetValue(int value) {
_readableInt.SetValue(value);
}
}
}
WritableInt is some private API consumer, which may reside in another assembly.
public sealed class WritableInt : ReadableInt.IPrivateConsumer {
ReadableInt _readableInt;
ReadableInt.PrivateApi _privateApi;
public WritableInt() {
_readableInt = new ReadableInt(this, Initialize);
}
void Initialize(ReadableInt.PrivateApi privateApi) {
_privateApi = privateApi;
}
public ReadableInt ReadOnlyInt { get { return _readableInt; } }
public void SetValue(int value) {
_privateApi.SetValue(value);
}
void ReadableInt.IPrivateConsumer.OnValueChanged() {
Console.WriteLine("Value changed!");
}
}
One can use the classes like this:
var writeableInt = new WritableInt();
var readableInt = writeableInt.ReadOnlyInt;
This is how the system works:
The private API (ReadableInt.PrivateApi) gains access to the main object (ReadableInt) private members by being an inner class. No up-casting/down-casting security breaches.
Notice that the ReadableInt.PrivateApi constructor is marked internal, so only ReadableInt can create the instances. I could not find a more elegant way to prevent anyone from creating a ReadableInt.PrivateApi from a ReadableInt object.
In general, ReadableInt needs a reference to the private API consumer to call it (notifications etc.). To decouple the public API from concrete private API consumers, the private API consumer is abstracted as the ReadableInt.IPrivateConsumer interface. ReadableInt receives the reference to a ReadableInt.IPrivateConsumer object through the constructor.
The private API controller object (ReadableInt.PrivateApi) is given to the creator (WriteableInt) via callback (Action<PrivateApi>) passed to the ReadableInt constructor. It's extremely ugly. Can anyone propose another way?
There is a small problem: WritableInt.OnValueChanged() method is private, but is effectively public as it's an interface method. This can be solved with a delegate or a proxy. Is there any other way?
This system works, but has some parts that I'm not proud of. I particularly dislike the initialization stage when all parts are linked together. Can this be simplified somehow?
How I do it
The question is quite interesting. I'm not in any way an expert in OOP (God! I wish I would!), but here is how I do it:
public interface IReadOnlyFoo
{
int SomeValue
{
get;
}
}
public class Foo: IReadOnlyFoo
{
public int SomeValue
{
get;
set;
}
}
public class Bar
{
private Foo foo;
public IReadOnlyFoo Foo
{
get
{
return foo;
}
}
}
It's not very secure, since you can cast IReadOnlyFoo to Foo. But my philosophy here is the following: when you cast, you take all the responsibility on yourself. So, if you shoot yourself in the foot, it's your fault.
How I would do if I were to avoid casting problem
First thing to consider here is that there are value types and reference types.
Value types
For the sake of this answer I would classify value types for pure data types (int, float, bool, etc.) and structures.
Pure data types
It is interesting that you explain your problem using int which is value type. Value types are get copied by assignment. So, you don't need any kind of wrapper or read only reference mechanics for int. This is for sure. Just make a read-only property or property with private/protected setter and that's it. End of story.
Structures
Basically, the same thing. In good designed code, you don't need any wrappers for structs. If you have some reference type values inside struct: I would say that this is a poor design.
Reference types
For reference types your proposed solution looks too complicated. I would do something like this:
public class ReadOnlyFoo
{
private readonly Foo foo;
public ReadOnlyFoo(Foo foo)
{
this.foo = foo;
}
public SomeReferenceType SomeValue
{
get
{
return foo.SomeValue;
}
}
}
public class Foo
{
public int SomeValue
{
get;
set;
}
}
public class Bar
{
private Foo foo;
public readonly ReadOnlyFoo Foo;
public Bar()
{
foo = blablabla;
Foo = new ReadOnlyFoo(foo);
}
}

Is it better to use this. before code? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I sometimes need to go online and find a tutorial for something. I am often finding that some people put code like this:
this.button1.Text = "Random Text";
Then I find code that is just like this:
button1.Text = "Random Text";
Is it better to use the this.whatever or does it not matter?
It depends. Here's an example class:
class A
{
private int count;
public A(int count)
{
this.count = count;
}
}
In this case, the "this." is mandatory because it disambiguates the reference on the left of the assignment. Without it, it is not clear to you reading the code whether "count" would refer to the parameter or the field. (It is clear to the compiler, which has rules to follow.) But in most cases, it is purely a matter of preference.
Write all your code to emphasize salient points to the reader. If you feel that it is important for the reader to clearly understand that an identifier refers to an instance member then use this. If you feel that its an unimportant and distracting implementation detail, don't. Use good judgment to make your code readable.
this is just to make it clear, in some cases we have to use this:
Differentiate between parameter and local member:
//local member
object item;
private void SomeMethod(object item){
this.item = item;//must use this
}
Pass the current class instance into another method:
public class SomeClass {
private void SomeMethod(SomeClass obj){
//....
}
private void AnotherMethod(){
SomeMethod(this);//pass the current instance into SomeMethod
//.....
}
}
Use in extension methods:
public static class SomeClassExtension {
public static void SomeClassMethod(this SomeClass obj){
//use obj as a reference to the object calling this method...
}
}
Call a constructor from another constructor (with different signature):
public Form1(string s) : this() {//Call the Form1() before executing other code in Form1(string s)
//......
}
Use for declaring indexers:
public class SomeClass {
//declare an index returning a string
public string this[int index] {
get {return ...}
set { ... }
}
}
Use auto-properties in struct:
public struct SomeStruct {
public object AutoProp1 {get;set;}
public object AutoProp2 {get;set;}
public SomeStruct() : this() //must use this
{
AutoProp1 = someObject;
AutoProp2 = someObject;
}
}
Cast the current instance to the based classes/types:
public class ClassB : ClassC {
//...
}
public class ClassA : ClassB {
public ClassA(){
((ClassC)this).MemberOfClassC ... ;//There might be some member in ClassC
//which is overridden in ClassA or ClassB, casting to ClassC can help we invoke the original member instead of the overridden one.
}
}
There might be some other uses of this, however I'll update later if I think out.
It does not matter, it is a matter of style. I tend to omit this, since it is just extra code to mentally parse.
The only case it matters is when there is a naming conflict between local and instance variables, in which case this can be used to disambiguate between a field and a local variable.
Here is an example of the type of situation where it does matter:
public class Foo
{
private string x;
public Foo(string x)
{
// x = x; Assigns local parameter x to x, not what we want
this.x = x; // Assigns instance variable x to local parameter x: this disambiguates between the two.
}
}
an example of using this can be to access class variable when you already have a similar variable in the scope. Otherwise it is mostly of choice.
Example
public class Test
{
public string firstName { get; set; }
public void temp(string firstName)
{
firstName = this.firstName;
}
}
In regards to fields the only case where this is explicitly needed is when there is a naming conflict:
public class Foo
{
private string bar;
public Foo(string bar)
{
this.bar = bar;
}
}
So some will prepend an underscore:
public class Foo
{
private string _bar;
public Foo(string bar)
{
_bar = bar;
}
}
Usually it will not matter. This reason why you might use this. is to explicit say that you want to reference a property/field that belong to the current class.
Again, there are not many occasions when you are likely to need this, but for example you might have a local variable with the same name as a class level property/field. Then you could use this..
For example:
class MyClass
{
string s = "1";
void MyFunction(string s)
{
//s = local value as passed in to function
//this.s = "1"
}
}
It doesn't usually matter. The this keyword "refers to the current instance of the class and is also used as a modifier of the first parameter of an extension method."
Check out this article.
http://msdn.microsoft.com/en-us/library/dk1507sz.aspx
generally it doesn't matter, but if you pass in a variable called, say button1, to a class method that already has a member called button1, then you'll need to disambiguate which one you really meant.
This is probably why people now use this. to explicitly say which variable you meant, if you use this practice all the time, you'll not get it wrong in the few cases where its important.
Of course, you could ensure that all member variables are uniquely named, say with a prefix like m_, but that's fallen out of fashion nowadays, people prefer to write out this.
It really depends on the situation.
http://msdn.microsoft.com/en-us/library/dk1507sz(v=vs.80).aspx
To qualify members hidden by similar names
To pass an object as a parameter to other methods
To declare indexers
As others have already pointed out, it is useful in distinguishing field/property with method variables, One other place where this is required is to invoke Extension methods on current instance. For example this.ExtensionMethod(); would work, but not just ExtensionMethod();
Other than that, its a matter of personal choice, some call it redundant and some like to use it. It totally depends on you and your team.
Personally I like to use this with class members, specially for Forms method if working on code-behind of winform, like this.Close();
For more discussion when to use this see: When do you use the "this" keyword?

What is the need of private constructor in C#?

What is the need of private constructor in C#?
I got it as a question for a C# test.
For example if you have a class that should only be created through factory methods. Or if you have overloads of the constructor, and some of them should only be used by the other constructors. Probably other reasons as well =)
If you know some design pattern, it's obvious: a class could create a new instance of itself internally, and not let others do it.
An example in Java (I don't know C# well enough, sorry) with a singleton-class:
class Meh
{
private Meh() { }
private static Meh theMeh = new Meh();
public static Meh getInstance() { return theMeh; }
}
Whenever you want to prevent direct instantiation of a class from outside of it, you'll use a private constructor. For example, prior to C# 2.0 which introduced static classes, you used a private constructor to accomplish roughly the same thing:
sealed class StaticClass {
private StaticClass() {
}
public static void DoSomething() {
}
}
When you want to prevent the users of your class from instantiating the class directly. Some common cases are:
Classes containing only static methods
Singletons
I can can recall few usages for it:
You could use it from a static factory method inside the same class
You could do some common work inside it and then call it from other contructure
You could use it to prevent the runtime from adding an empty contructure automatically
It could be used (although private) from some mocking and ORM tools (like nhibernate)
For example when you provide factory methods to control instantiation...
public class Test(){
private Test(){
}
void DoSomething(){
// instance method
}
public static Test CreateCoolTest(){
return new Test();
}
}
Private constructors are used to prevent the creation of instances of a class when there are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class. If all the methods in the class are static, consider making the entire class static. For more information see Static Classes and Static Class Members.
class NLog
{
// Private Constructor:
private NLog() { }
public static double e = System.Math.E; //2.71828...
}
The following is an example of a class using a private constructor.
public class Counter
{
private Counter() { }
public static int currentCount;
public static int IncrementCount()
{
return ++currentCount;
}
}
class TestCounter
{
static void Main()
{
// If you uncomment the following statement, it will generate
// an error because the constructor is inaccessible:
// Counter aCounter = new Counter(); // Error
Counter.currentCount = 100;
Counter.IncrementCount();
System.Console.WriteLine("New count: {0}", Counter.currentCount);
}
}
While this link is related to java, I think it should help you understand the reason why as the idea is pretty much the same.
Private constructors prevent a class from being explicitly instantiated by callers. There are some common cases where a private constructor can be useful:
classes containing only static utility methods
classes containing only constants
type safe enumerations
singletons
You can use it with inheritance in a case where the arguments to the constructor for the base class are of different types to those of the child classes constructor but you still need the functionality of the base class in the child class eg. protected methods.
Generally though this should be avoided wherever possible as this is a bad form of inheritance to be using.
I'm late to the game, but reading through all the other answers, I don't see this usage mentioned:
I use private constructors in scenarios where I have multiple (public) constructors, and they all have some code in common. With constructor chaining, the code becomes really neat and DRY.
Remember, the private readonly variables can only be set in constructors, so I can't use a regular method.
Example:
public class MyClass
{
private readonly int _a;
private readonly int _b;
private readonly string _x;
public MyClass(int a, int b, string x)
: this(x)
{
_a = a;
_b = b;
}
public MyClass()
: this("(not set)")
{
// Nothing set here...
}
private MyClass(string x)
{
_x = x;
}
}
Basically you use private constructors when you are following a singleton design pattern. In this case, you have a static method defined inside the class that internally calls the private constructor.
So to create the instance of the class for the first time, the user calls the classname.static_method_name. In this method, since the class's object doesn't yet exist, the static method internally calls the private constructor and returns the class's instance.
If the class's instance already exists, then the static method simply returns the instance to the calling method.
And of course you can use private constructor to prevent subclassing.

How can one type access a private setter of another type's property?

All I need is a way to make a property of one class only 'settable' from one other class (a sort of manager class).
Is this even possible in c#?
My colleague 'reliably' informs me that I have a design flaw, but I feel I should at least ask the community before I concede defeat!
No, it's not really possible to do this in any clean way in C#. You probably have a design flaw ;-)
You can use the internal modifier, which lets all types in the same assembly access the data (or nominated assemblies if using [InternalsVisibleTo] - but no: there is no friend equivalent in C#.
For example:
public string Foo {get; internal set;}
You have a design flaw. Also, don't be paranoid about data hiding. Here's 3.5's way to do it:
class Program
{
static void Main(string[] args)
{
Managed m = new Managed();
Console.WriteLine(m.PrivateSetter);
m.Mgr.SetProperty("lol");
Console.WriteLine(m.PrivateSetter);
Console.Read();
}
}
public class Managed
{
private Manager _mgr;
public Manager Mgr
{
get { return _mgr ?? (_mgr = new Manager(s => PrivateSetter = s)); }
}
public string PrivateSetter { get; private set; }
public Managed()
{
PrivateSetter = "Unset";
}
}
public class Manager
{
private Action<string> _setPrivateProperty;
public Manager(Action<string> setter)
{
_setPrivateProperty = setter;
}
public void SetProperty(string value)
{
_setPrivateProperty(value);
}
}
Here's how we'd do it in pre-lambda days:
public class Managed
{
private Manager _mgr;
public Manager Mgr
{
get { return _mgr ?? (_mgr = new Manager(this)); }
}
public string PrivateSetter { get; private set; }
public Managed()
{
PrivateSetter = "Unset";
}
public class Manager
{
public void SetProperty(string value)
{
m.PrivateSetter = value;
}
private Managed m;
public Manager(Managed man)
{
m = man;
}
}
}
The best way to do it would be:
/// <summary>
/// Gets or sets foo
/// <b>Setter should only be invoked by SomeClass</b>
/// </summary>
public Object Foo
{
get { return foo; }
set { foo = value; }
}
When you have some complex access or inheritance restriction, and enforcing it demands too much complexity in the code, sometimes the best way to do it is just properly commenting it.
Note however that you cannot rely on this if this restriction has some security implications, as you are depending on the goodwill of the developer that will use this code.
You cannot do that on that way, but you can access a property's setter method from a derived class, so you can use inheritance for the purpose. All you have to do is to place protected access modifier. If you try to do so, your colleague is right :). You can try doing it like this:
public string Name
{
get{ return _name; }
protected set { _name = value; }
}
keep in mind that the set method of the property is only accessible from the derived class.
Or you could have these two classes in an assembly alone and have the setter as internal. I would vote up for the design flaw though, unless the previous answer by milot (inheriting and protected) makes sense.
You could do:
public void setMyProperty(int value, Object caller)
{
if(caller is MyManagerClass)
{
MyProperty = value;
}
}
This would mean that you could use a 'this' pointer from the calling class. I would question the logic of what you're attempting to achieve, but without knowing the scenario I can't advise any futher. What I will say is this: if it is possible to refactor your code to make it clearer, then it is often worthwhile doing so.
But this is pretty messy and certinly NOT fool-proof ... you have been warned!
Alternativly...
You could pass a delegate from the Class with the Property (Class A) to the Manager Class (Class B). The delegate can refer to a private function within A to allow B to call that delegate as any normal function. This precludes that A knows about B and potentially that A is created before B. Again... messy and not fool-proof!
You can achieve to this by making a Public property in your "settable class" that will inherit from the real class that will have a protected property... this way only the inherit class can SET and not class that doesn't inherit. But the drawback is that you will require to have an inherit class...
Reflection, though I would agree that having to do this just to get around an access modifier is probably an indication of a bad design.
public class Widget
{
private int count;
public int Count
{
get { return this.count; }
private set { this.count = value; }
}
}
public static class WidgetManager
{
public static void CatastrophicErrorResetWidgetCount( Widget widget )
{
Type type = widget.GetType();
PropertyInfo info = type.GetProperty("Count",BindingFlags.Instance|BindingFlags.NonPublic);
info.SetValue(widget,0,null);
}
}
The reason this is a design flaw is because it seems muddled between the scope of the two objects.
The properties of a class should be accessible in the context of that class, at least internally.
It sounds like the settable property on your item class is really a property of the manager class.
You could do something similar to what you want by closely coupling the two classes:
public class MyItem {
internal MyItemManager manager { get;set; }
public string Property1 {
get { return manager.GetPropertyForItem( this ); }
}
}
Unfortunately this isn't great design either.
What your looking for is what C++ calls a Friend class but neither c# or vb has this functionality. There is a lot of debate as to the merit of such functionality since it almost encourages very strong coupling between classes. The only way you could implement this in c# would be with reflection.
If your goal is to have a class Foo let some property (e.g. Bar, of type Biz) to be changed by some other object, without exposing it publicly, a simple way to do that is to have an instance of Foo which is supposed to be changeable by some other object to pass that other object an Action<Biz> which points to a private method that changes Bar to the passed-in value. The other object may use that delegate to change the Bar value of the object that supplied it.
If one wishes to have give all instances of some type Woozle the ability to set the Bar value of any instance of Foo, rather than exposing such abilities on a per-instance basis, one may require that Woozle have a public static method Woozle.InstallFooBarSetter which takes a parameter of type Action<Foo, Biz> and one of type Object. Foo should then have a static method WoozleRequestBarSetter which takes an Object, and passes it to Woozle.InstallFooBarSetter along with an Action<Foo,Biz>. The class initializer for Woozle should generate a new Object, and pass it to Foo.RequestBarSetter; that will pass the object to Woozle.InstallFooBarSetter along with a delegate. Woozle can then confirm that the passed-in object is the one that it generated, and--if so--install the appropriate delegate. Doing things this way will ensure that nobody but Woozle can get the delegate (since the delegate is only passed to Woozle.InstallFooBarSetter), and Woozle can be sure its delegate comes from Foo (since nobody else would have access to the object that Woozle created, and Woozle.InstallFooBarSetter won't do anything without it).
if it is a design flaw depends on what you want to do. You could use the StackTrace class from System.Diagnostics to get the Type of the class setting your property and then compare to the type you want to allow setting yor property..but maybe there are better ways for performing something like this (e.g. boxing)

Categories