I have implemented the following class:
public class ClassAllocator<T>
where T : new()
{
public delegate T Allocator();
T obj;
Allocator allocator = () => new T();
public ClassAllocator( T obj )
{
this.obj = obj;
}
public ClassAllocator( T obj, Allocator allocator )
{
this.obj = obj;
this.allocator = allocator;
}
public T Instance
{
get
{
if( obj == null )
{
obj = allocator();
}
return obj;
}
}
}
I feel like something this simple & useful should be in .NET somewhere. Also, I realize that the class I made is somewhat incorrect. The class is designed to work with objects that don't have a default constructor, yet my 'where' clause requires it in all cases.
Let me know if there is something in .NET I can use so I can get rid of this class, as I would hate to continue using a reinvented wheel.
Thanks!!!!
UPDATE:
I'm using .NET 3.5. Sorry I didn't mention this before, I wasn't aware it was relevant until a few good answers started flowing in :)
Sounds like you're looking for the Lazy<T> Class.
Lazy<T> Class
Provides support for lazy initialization.
Lazy initialization occurs the first time the Lazy<T>.Value property is accessed
The Lazy class
Related
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.
I am a Java programmer trying to transition to C# and I'm hoping there's a way to do something in C# that I'm accustomed to in Java: overriding a method in the declaration of an abstract object like so:
//This is the way I do it in Java and want to do in C#
Keyword k = new Keyword("quit"){
public abstract void do(String context){
//TODO Do stuff
}
};
This is for some text game stuff I've been doing for a while in Java. I've looked into abstract and virtual and anonymous classes but none of them do exactly this. Abstract and virtual want me to create a whole new subclass, but this would be time consuming and unfeasible on a large scale. Anonymous classes don't (as far as I can tell) enable me to override methods, just fields and don't provide any stabilization for me to rely on.
If there is a way to do this or something similar please explain. Thanks for your time.
That doesn't work in C#. You'll have to create a new class that inherits from Keyword.
public class MyKeyword : Keyword
{
public MyKeyword(string s) : base(s)
{ }
public override void do(string context)
{
// TODO: Do stuff.
}
}
Anonymous Types in C# aren't classes that you can provide any public methods for. They only have properties, and are intended to be a quick, intra-method way of pasing complex data from one line to the next.
To be honest, I didn't know you could do what you show in Java. That is, if I'm understanding it as kind of an in-line class derivation.
Brian Rasmussen mentions using a delegate. That would look something like this:
public delegate void DoSomething(string context);
public class Keyword
{
public DoSomething Do;
private void CallsDo()
{
if (Do != null) Do("some string");
}
}
Then you can assign to it:
Keyword k = new Keyword();
k.Do = (ctx) => { /* Do something with ctx string */ };
Delegates are probably what you are after.
You can utilize a delegate for this approach: Note the example
public class Keyword
{
public delegate void Do();
}
//Area of Execution
{
//...
Keyword k = new Keyword();
k.Do = delegate()
{
Console.Writeln("Anonymous Inner function assigned to a callback function i.e a Delegate!");
};
}
These are much like function pointers in C/C++ but that may mean nothing to you depending on your background.
A delegate is, in the simplest terms, a type-safe object that encapsulates a method/function. What this means is that it maintains a reference to the method or methods and can invoke them later through the delegate object rather than explicitly on the method(s) themselves. You can assign an anonymous function to the right hand side much the same as you can to a method in Java as you described.
hope this helps. Read more here for delegates in-depth
Delegates
I don't know:
if this works.
if it's a good idea.
what it is called in order
to find out more about it.
But I think the intent is fairly apparent.
public static class DebugLogic
{
public static bool ThrowIfNull = false;
public static T OrNew<T>(this T obj) where T : class
{
if (obj != null) return obj;
else if (ThrowIfNull) throw new ArgumentNullException(//to do...);
else return Activator.CreateInstance<T>();
}
}
Intended usage:
var customer = order.Sale.OrNew().Customer.OrNew().Name
What am I doing? Is this insane or helpful? It seems helpful.
I think the idea of having an OrNew method is fine. Especially if you're striving to make a fluent interface. However I would change 3 things about it
Don't have a hidden flag that controls the behavior (ThrowIfNull). This makes it impossible for someone to read an OrNew call an understand what it does.
Use a new constraint in favor of the less safe Activator.CreateInstance<T>() call
I'd call it something other than DebugLogic. Generally (but not always) extension method containers end with the Extensions .
For example
public static class LogicExtensions {
public static T OrNew<T>(this T obj) where T : class, new() {
if (obj != null) {
return obj;
}
return new T();
}
}
The name of this operation is clearly: DefaultIfNull
I've found a nice link on C++ Tenmplates:
http://www.cplusplus.com/doc/tutorial/templates/
and needed something similar in C#. I have a solution that seems to work but wanted opinions of others in how it relates to the above link, specifically the specialization section.
Here is a proof of concept I came up with:
public abstract class Piece
{
public object Value { get; set; }
}
public class Rook : Piece
{
public void Capture()
{
int i = (int)this.Value;
}
}
public class Pawn : Piece
{
public void CaptureEnPassant()
{
string s = (string)this.Value;
}
}
public class PieceFactory<P, T> where P : Piece, new()
{
P p;
public PieceFactory(T value)
{
p = new P();
p.Value = value;
}
public P GetPiece()
{
return p;
}
}
and then finally to call into the factory I do this:
var piece = new PieceFactory<Pawn, string>("exd6").GetPiece();
piece.CaptureEnPassant();
I've seen different solutions like using extension methods and other ways...
Just wanted to see if my way of thinking is along the lines of good patterns.
THanks so much,
David
My opinion is that your sketch is far more complex and confusing than necessary. Why does the base class have a "value" that has different meanings and different types in each derived class? Why is there a factory that takes a type parameter that must be of a particular type argument, and if it is not, then the program crashes at runtime? Get rid of all that brittle, confusing, fragile stuff. If a pawn needs a string, then make a public constructor on Pawn that takes a string, end of story. There's no need for the factory pattern at all here.
Don't be so in love with the tool that you build stuff out of it that doesn't actually make any sense. Generic types are great for things like collection classes. They're not a good fit for the chess domain.
FYI I tried converting my own template-programmed chess engine into C# for fun, and found it was slower by roughly a factor of 20 across the board [sic].
That includes stuff like parsing the gamefile format. Position lookup and move generation just had a lot of mechanical sympathy in the C++ version, that applying all the tricks could not make up for:
compiletime optimization
non-shared generics (mono specific - see here, e.g.)
unsafe code (pinned arrays, raw pointers),
unchecked blocks (as in array bounds/arithmetic overflow
value typed arrays and ref passing
short, inlinable functions
garbage prevention (custom allocation in preallocated 'realms' (just large arrays of structs preallocated)
That said, the performance benefit from using generic collections is significant, esepcially for, say List<T> where T : struct. Note however, the caveats from the link above (especially for the new constraint which has rather pathetic performance on MS. NET due to code sharing; it is basically as slow as using reflection to call the constructor, even for value types).
YMMV, but in the end I'd say
1. Go with the C# way. If you must optimize, do it the C# way
2. If all else fails, resort to P/Invoke (C++/CLR is a sweet spot if you target Windows)
I would just use generics on your base class. Does this break something in your code?
void Main()
{
var factory = new PieceFactory<Rook, int>(20);
factory.GetPiece().Dump();
}
abstract class Piece<TValue>
{
public TValue Value { get; set; }
}
class Rook : Piece<int>
{
public int Capture()
{
// Do something...
return base.Value;
}
}
class Pawn : Piece<string>
{
public string EnPassant()
{
// Do something...
return base.Value;
}
}
class PieceFactory<TKey, TValue> where TKey : Piece<TValue>, new()
{
private readonly TKey piece;
public PieceFactory(TValue value)
{
this.piece = new TKey();
this.piece.Value = value;
}
public TKey GetPiece()
{
return this.piece;
}
}
I have also put some access keywords (like this and base) and a readonly modifier in your factory.
the following code used to work fine under vs2008:
namespace N2.Engine.Globalization
{
public class DictionaryScope : Scope
{
object previousValue;
public DictionaryScope(IDictionary dictionary, object key, object value)
: base(delegate
{
if (dictionary.Contains(key))
previousValue = dictionary[key];
dictionary[key] = value;
}, delegate
{
if (previousValue == null)
dictionary.Remove(key);
else
dictionary[key] = previousValue;
})
{
}
}
}
but now it reports An object reference is required for the non-static field, method, or property 'N2.Engine.Globalization.DictionaryScope.previousValue'
It seems something changed in the compiler? Any workarounds?
update:
regarding the suggestion to use a virtual method. This probably wouldn work either, as the virtual method would get called from the base constructor, which I believe is also not possible?
Here is the implementation of the Scope (base class):
public class Scope: IDisposable
{
Action end;
public Scope(Action begin, Action end)
{
begin();
this.end = end;
}
public void End()
{
end();
}
#region IDisposable Members
void IDisposable.Dispose()
{
End();
}
#endregion
Update:
§ 7.5.7 This access
A this-access consists of the reserved word this.
this-access:
this
A this-access is permitted only in the block of an instance constructor, an instance method, or an instance accessor.
This is none of these. The 4.0 compiler looks to be correct. Presumably it isn't happy because this in essence provides access to this at a point when the type isn't initialized. Maybe ;-p
Note that I expect that it isn't really the this.someField that causes this - more that the use of a field causes this to be captured, meaning it wants to hoist the this instance onto a compiler-generated class - as though you had written:
public MyCtor() : base( new SomeType(this).SomeMethod ) {...}
The C# 3.0 compiler spots the above abuse of this.
Reproduced. Investigating. It looks like an issue resolving the implicit this in the constructor chaining.
The most likely workaround would be to use a virtual method instead of a delegate, and simply override it in the derived class.
One workaround would be to pas the instance in as an argument, so the delegate becomes "obj => obj.whatever...", and use theDelegate(this);.
Simpler repro:
public class MyBase {
public MyBase(Action a) { }
}
public class MySub : MyBase {
private string foo;
// with "this.", says invalid use of "this"
// without "this.", says instance required
public MySub() : base(delegate { this.foo = "abc"; }) { }
}
I would need to check the spec, but I'm not sure whether this is valid in this context... so the 4.0 compiler could be correct.
Add:
static object previousValue;