Map object instance to 'this'? - c#

This is just a 'out-of-curiosity' question, so I can't provide a real world example based on a current problem, but a little dummy code should suffice. What I'm wondering is if there is a straight-forward (and especially fast) way to map an instance of an object to 'this' (a current instance of the exact same type, with access to private members etc.)
public class MyObject {
public MyObject(MyObject other) {
// of course, won't work
this = other;
}
}
All examples and how-to's I've seen take excessive use of reflection, even building up complete expression trees or using frameworks like Automapper, all with their own limitations when the idea seems 'fairly trivial'. Why isn't it just possible to copy over all pointers/references etc. from one place in memory to another, given that the allocated space etc. is exactly the same?

AFAIK, there isn't a straight forward way to do that for the own instance (this). And I imagine that copying the data from the other instance to this would suffice. What might be an alternative for you is work with a static instance, but this has some particularities if you need to work with more then one instance.
public class MyObject {
private static MyObject _instance;
public static MyObject Instance
{
get { return _instance; }
set { _instance = value; }
} }
PS: I wrote this post from my cell, so forgive me if you run into minor errors, as I wasn't able to test it before posting. I will update the post as soon as I'm able to test the code.

If this was possible you´re simply referencing other by a new reference, but not copy its content to a new instance of MyObject. So your constructor would simply return a new reference to the already existing instance. What you need is a completely new instance of MyObject, don´t you? So you have to create one using one of its constructors. If you have a copy-constructor that achieves this you´re fine:
public class MyObject {
public MyObject(MyObject other) {
this.Prop1 = other.Prop1;
}
}
Of course there are some shorter (but not neccesarily saver) appraoches - e.g. using reflection and simply copy all property values from one instance to another one. However basically you still end up creating a completely new instance by setting of of its members appropriately.
The reflection-code may look similar to this:
public class MyObject {
public MyObject(MyObject other) {
var props = typeof(MyObject).GetProperties();
foreach(var p in props)
{
p.SetValue(this, p.GetValue(other));
}
}
}
However this only applies to the public properties, you have to do this with the fields and the private or internal members also.

Related

Getting the type of another nested class from the same "parent" class

I'm attempting to make a namespace for the first time while learning programming. I am hoping there is a way around the problem I've run into that isn't particularly messy, but essentially I have a class object that keeps two dictionaries of two nested class objects. I need to be able to pass the Dictionary of NestedClassA to NestedClassB or to allow NestedClassB to access it in some way... Here is an example of what I'm trying to do:
namespace MyFirstNamespace
{
public class BossClass
{
public Dictionary<int, NestedClassA> DictionaryA = new Dictionary<int, NestedClassA>();
public Dictionary<int, NestedClassB> DictionaryB = new Dictionary<int, NestedClassB>();
public class NestedClassA { ...arbitrary class definition... }
public class NestedClassB
{
public Dictionary<int, NestedClassA> PassedDictionary;
public NestedClassB() { }
public NestedClassB(Dictionary<int, NestedClassA> tempDic))
{
PassedDictionary = tempDic;
}
}
public BossClass() { ... arbitrary constructor ... }
...arbitrary dictionary population methods...
function void CreateAClassBInstance()
{
DictionaryB[n] = new NestedClassB(n, DictionaryA);
}
}
}
My problem seems to be that I can't typecast "NestedClassA" within "NestedClassB" because it doesn't recognize the type. Is it possible to access the "NestedClassA" type within B? Nothing I've tried has worked. Do I have to pass the instance of "BossClass" so I can reference type by "Dictionary<int, MyFirstNamespace.BossClassInstance.NestedClassA>"?
Any help would be appreciated. To be clear, I want a REFERENCE variable passed to NestedClassB of a Dictionary of all NestedClassA members so they can be manipulated by NestedClassB. It can't be a clone. I know this seems like ridiculous implementation, but it seems the most effective, if it's possible, for what I'm trying to do.
EDIT: maybe I shouldn't be nesting them at all, but it would make them much easier to serialize, which is why I really wanted to do it this way.
(EDIT - fixed typo where I forgot to insert "public" before constructors.)
There doesn't seem to be anything particularly wrong with your implementation of NestedClassB other than you need to make your constructors public if you wish to instantiate an instance of NestedClassB. By default in .Net, objects are passed by reference to function parameters, so you will have the same instance of Dictionary<int, NestedClassA> in NestedClassB.
Here is the adjusted class:
public class NestedClassB
{
private readonly Dictionary<int, NestedClassA> _PassedDictionary;
public NestedClassB() { }
public NestedClassB(Dictionary<int, NestedClassA> tempDic) {
_PassedDictionary = tempDic;
}
public Dictionary<int, NestedClassA> PassedDictionary {
get { return _PassedDictionary; }
}
}
Note that I changed PassedDictionary to a property instead of a member variable. Most serializers will ignore member variables and only serialize properties. If you need to deserialize, you'll need to remove the readonly from the private member variable and add a setter.
The function at the bottom of your code snippet doesn't look right. You'll want to make it look like:
private void CreateAClassBInstance()
{
DictionaryB[n] = new NestedClassB(DictionaryA);
}
For anyone trying to do this: passing the instance of the wrapper class is necessary for the nested class to access methods or variables of the wrapper class. This can be done with "this" keyword.

Use an anonymous method to avoid creating a single-use object?

I'm trying to refactor a method that parses through a file. To support files of arbitrary size, the method using a chunking approach with a fixed buffer.
public int Parse()
{
// Get the initial chunk of data
ReadNextChunk();
while (lengthOfDataInBuffer > 0)
{
[parse through contents of buffer]
if (buffer_is_about_to_underflow)
ReadNextChunk();
}
return result;
}
The pseudo code above is part of the only public non-static method in a class (other than the constructor). The class only exists to encapsulate the state that must be tracked while parsing through a file. Further, once this method has been called on the class, it can't/shouldn't be called again. So the usage pattern looks like this:
var obj = new MyClass(filenameToParse);
var result = obj.Parse();
// Never use 'obj' instance again after this.
This bugs me for some reason. I could make the MyClass constructor private, change Parse to a static method, and have the Parse method new up an instance of Parse scoped to the method. That would yield a usage pattern like the following:
var result = MyClass.Parse(filenameToParse);
MyClass isn't a static class though; I still have to create a local instance in the Parse method.
Since this class only has two methods; Parse and (private) ReadNextChunk, I'm wondering if it might not be cleaner to write Parse as a single static method by embedding the ReadNextChunk logic within Parse as an anonymous method. The rest of the state could be tracked as local variables instead of member variables.
Of course, I could accomplish something similar by making ReadNextChunk a static method, and then passing all of the context in, but I remember that anon methods had access to the outer scope.
Is this weird and ugly, or a reasonable approach?
This maybe suitable more to code review.
However, these are my comments about your design:
I don't think it will matter much about obj instance only used once. If you bugged with it, there are 2 ways to trick it:
Use of another method such as:
public int Parse()
{
var obj = new MyClass(filenameToParse);
return obj.Parse();
}
Make the MyClass implement IDisposable and wrap it in using statement. I don't recommend this since usually IDisposable has logic in their Dispose() method
I think it is better to make your MyClass accept parameter in Parse to Parse(string fileNameToParse). It will make MyClass as a service class, make it stateless, reusable and injectable.
Regarding impact to static class. First it add coupling between your consumer and MyClass. Sometimes if you want to test / unit test the consumer without using the MyClass parser, it will be hard / impossible to mock the MyClass into something you want.
All you need is a static parse method that creates an instance, much like what you suggest in your question
public class MyClass
{
// your existing code.... but make the members and constructor private.
public static int Parse(string filenameToParse)
{
return new MyClass(filenameToParse).Parse();
}
}
then
just use it like you suggest...
var result = MyClass.Parse(filenameToParse);
MyClass isn't a static class though; I still have to create a local
instance in the Parse method.
You don't need a static class to be able to leverage static methods. For example this works fine:
public class MyClass
{
public static string DoStuff(string input)
{
Console.WriteLine("Did stuff: " + input);
return "Did stuff";
}
}
public class Host
{
public void Main()
{
MyClass.DoStuff("something");
}
}

Class extending - best practice/best solution

First thing to note - I KNOW DELEGATION AND DECORATOR PATTERNS!
Second - I am using C# .NET 4.0, so if you come up with a solution that is specific for it, that's fine. But if solution will work for any OOP language and platform, that would be great.
And here the question goes...
I have a partial class (lets name it Class1), which I cannot modify. Thus, I can just extend it or/and inherit from it. This class provides a perfect data model for me, the only thing I need is to add some attributes to its properties (for validation, defining label text value in MVC etc - for now, I do not need answers like 'you can do what you need without attributes', that's not the matter of my question).
It is not a problem to use another class as a data model, so I can, say, create Class2 : Class1 and use Class2 as a model. Properties that need attributes would be defined as public new <type> <propertyname>. This will limit me to rewriting only the properties that need attributes, leaving all other untouched.
The smaller problem is that I do not what to redefine getters and setters for the properties, as all they gonna contain is return base.<propertyname> and base.<propertyname> = value, and if there are lots of such properties, this means lots of "stupid" coding. Is there a way to avoid this?
The bigger problem is that I have to parametrize my Class2 with Class1 instance and make something like class2.<propertyname> = class1.<propertyname> for each single property I have - too much of "stupid" coding. I can avoid it using reflection - find all properties with public getters and setters in Class1 and call prop.SetValue(child, prop.GetValue(parent, null), null); in the loop. This provides a generic function for simple cases, which is quite fine, as I mostly have simple models - lots of properties with public getters and setters without body and another logic. But I want more generic solution, and I do not like reflection. Any ideas?
Here goes the full code of the extension method that creates Class2 basing on Class1
public static Child ToExtendedChild<Parent, Child>(this Parent parent)
where Child : Parent, new()
{
Child child = new Child();
var props = typeof(Parent).GetProperties().Where(p => p.GetAccessors().Count() >= 2);
foreach (var prop in props)
{
prop.SetValue(child, prop.GetValue(parent, null), null);
}
return child;
}
(by the way, this method may not ideally implement my solution, so any corrections would also be appreciated)
Thanks in advance!
The smaller problem doesn't seem to be much of a problem. Maybe I'm misunderstanding the question, but assuming you're simply deriving a subclass, there should be no reason to redefine either the properties or their associated getters/setters.
The bigger problem might be resolved using something a little simpler. Using reflection for a lot of your object initialization seems a little expensive. If you're dealing with a class that is primarily a big bag or properties, maybe you should as if you need access to all of those properties in any given situation. You mention MVC and validation, is the entire model being used in the controller method you're validation is taking place in? If not, why not look at using a viewmodel that only exposes those pieces you need in that method?
Your reflection initializer is interesting, but if you're going to be doing a lot of this then you might consider investing a little time with Automapper. Otherwise maybe consider moving away from a generic solution to something that just tackles the problem at hand, i.e. mapping properties from an instance of an object to another instance of a derived object. Maybe you can create a copy constructor in the parent class and use that in your derived class?
public class Foo {
public string PropOne { get; set; }
public string PropTwo { get; set; }
public Foo(string propOne, string propTwo) {
PropOne = propOne;
PropTwo = propTwo;
}
public Foo(Foo foo) {
PropOne = foo.PropOne;
PropTwo = foo.PropTwo;
}
}
public class Pho : Foo {
// if you have additional properties then handle them here
// and let the base class take care of the rest.
public string PropThree { get; set; }
public Pho(string propOne, string propTwo, string propThree)
: base(propOne, propTwo) {
PropThree = propThree;
}
public Pho(Pho pho) : base(pho) {
PropThree = pho.PropThree;
}
// otherwise you can just rely on a copy constructor
// to handle the initialization.
public Pho(Foo foo) : base(foo) {}
}
I assume the partial class is generated code, it makes the most sense given your scenario.
I know of one way to do this, but depending on how the attribute gets crawled, it may not work.
// Generated Code
public partial Class1
{
public string Foo { get { ... } }
}
// Your Code
public interface IClass1
{
[MyAttribute]
public string Foo { get; }
}
public partial Class1 : IClass1
{
}
If someone were to look at attributes by using GetCustomAttributes with inheritance, then I think they would get this attribute.
As an aside, whenever I see generated code that doesn't have virtual properties it makes me cry a little bit inside.
To address your bigger question, why don't you just make Class2 a wrapper for Class1. Instead of copying all of the properties you can just give Class2 an instance of Class1 in the constructor, store it locally and make all of your properties pass-throughs. It means some hand coding, but if you're building a Class2 by hand anyway and want to decorate it with a bunch of attributes, well, you're hand coding Class2 anyway.

Dynamically extending a type at runtime?

I have the need to extend instances of various types at runtime. Most of the time, I need to work with instances of the original type, however in a few circumstances, I need to create kind of an extension-wrapper around those types that add a couple pieces of contextual information. Something along the lines of the following (which is not actually valid .NET/C# code...but it illustrates the point):
public abstract class BaseClass
{
// ...
}
public class Concrete1: BaseClass
{
// ...
}
public class Concrete2: BaseClass
{
// ...
}
public class WrapperExtender<T>: T // Extending from T here is actually invalid!
where T: BaseClass
{
public WrapperExtender(T extensionTarget)
{
m_extensionTarget = extensionTarget;
}
private readonly T m_extensionTarget;
public object ContextualReference { get; }
public int ContextualValue { get; }
// DERP: Would need to implement overrides of T here...buuut...can't...
}
// In use, special case:
var instance = new Concrete1();
var extendedInstance = new WrapperExtender(instance);
var processor = new SomeProcessorRequiringExtendedInstance();
processor.DoProcessing(extendedInstance);
Another example of this would probably be Microsoft Entity Framework v4.0, or nHibernate. Both of these frameworks provide dynamically extended instances of your entity types, wrapping them internally to provide, at runtime, the hooks required to keep a data/object/session context up to date with changes made to your entity instances. My needs are not nearly as complex, and the generics scenario above would work beautifully, if only there was a way to blend generics and dynamic typing somehow.
Anyway, I'm hoping someone knows how to achieve the above scenario. Or, perhaps even better, someone knows a better solution. I don't care much for the idea of dynamically extending a type like that at runtime (it doesn't make as much sense as it does in the EF/nHibernate scenario.) At the moment, its the only thing I can really think of that will provide me with the information I need in the processor for each type passed in to DoProcessing.
The problems that EF etc are solving is different, and relates to tihngs like lazy loading, etc. I'm simply not sure that the level of complexity that dynamic subclassing requires is worth it for this scenario. A few thoughts, though:
have a property bag in your object for flexible additional properties; if necessary the property-bag can be exposed to data-binding APIs via ICustomTypeDescriptor
simply wrap your object in an implementation-specific tuple that contains the existing object and the additional properties (no subclassing)
It is a shame that C# doesn't support "mixins", which would also be a nice way of implementing this type of thing with interfaces.
I know that this can be accomplished using dynamicproxy (which is what NHibernate uses to accomplish this task) which you can find out more about here:
DynamicProxy Page
DynamicProxy tutorial
If all you need is some additional properties, why not just create a context property in BaseClass?
something like this, where ContextBag is either a generic collection class or specially defined context collection:
Public ContextBag Context
{
get;
set;
}
When setting/accessing the context, you will be using syntax like this:
SubClass.Context.GetInt(ContextDefinition, ContextName);
SubClass.Context.Add(ContextDefinition, ContextName, ContextValue);
Found a better solution than temporarily extending. I created an actual context object that contained the state I needed available. Whenever that context exists, I initialize the context and set a static property that can be used to retrieve the context object from anywhere, alleviating the need to update all the dependencies of my larger process to take the context in as a parameter (which isn't always possible, as sometimes the calls are made in other contexts.)
public class SomeContext
{
public SomeContext(object stateData1, object stateData2)
{
StateData1 = stateData1;
StateData2 = stateData2;
}
public virtual object StateData1 { get; private set; }
public virtual object StateData2 { get; private set; }
[ThreadStatic]
private static SomeContext m_threadInstance;
public static SomeContext Current
{
get
{
return m_threadInstance;
}
set
{
if (value != null && m_threadInstance != null)
throw new InvalidOperationException("This context has already been initialized for the current thread.");
m_threadInstance = value;
}
}
}
public class SomeContextScope: IDisposable
{
public SomeContextScope(object stateData1, object stateData2)
{
if (SomeContext.Current == null)
{
SomeContext context = new SomeContext(stateData1, stateData2);
SomeContext.Current = context;
m_contextCreated = true;
}
}
private bool m_contextCreated;
public void Dispose()
{
if (m_contextCreated)
{
SomeContext.Current = null;
}
}
}
public class ComplexProcessor
{
public ComplexProcessor(...) // Lots of dependencies injected
public void DoProcessing(BaseClass instance)
{
// do some work with instance
if (SomeContext.Current != null)
{
// do contextually sensitive stuff for SomeContext with instance
// call a dependency that does contextually sensitive stuff
}
// do some more work with instance
// call a dependency that does contextually sensitive stuff
if (SomeOtherContext.Current != null)
{
// do contextually sensitive stuff for SomeOtherContext with instance
// call a dependency that does contextually sensitive stuff
}
// call a dependency that does contextually sensitive stuff
}
}
// The original setup of the context and initiation of processing
public void SomeOperation(...)
{
using (SomeContextScope scope = new SomeContextScope(stateData1, stateData2))
{
// ... do some work
var processor = complexProcessorFactory.CreateInstance();
processor.DoProcesing(data);
// ... do more work
}
}
I like the way this works. Context is the state within which behavior executes. It has always felt clunky to me to have to pass contextual data around with other objects, and have dozens of methods or method overloads that take in and pass along various forms of contextual data. By setting up a context object that is globally available for the duration of that context, my code is a lot cleaner, and my dependencies are more concise. It should be mockable too, since the Current property is read/write, I can create a mock context in a BDD specification or TDD unit test whenever one is required without a lot of hassle.

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