❔ How can I create a fill method that creates unique elements?
I have the following 2D array method that is for basic types and references.
This works when I want basic types and every reference value pointing to the same object. I want to keep this method for those, which is the most common. However, I need a similar one that makes every element unique using
This works when I want basic types and every reference value pointing to the same object. I want to keep this method for those, which is the most common. However, I need a similar one that makes every element unique using
new
. For example, every Wall object in the array is unique. Each wall has its own properties. I do want the method generic so it allows any object of a class.
Here's the idea:
Again, this is just example code of what I want to see happen, but it has a compile error that T does not have a new() constraint. Is there a good solution to this?
For reference, my class is written as this:
15 Replies
i would just give it a a factory method:
@cap5lut I'm not familiar with factory methods in C#. I used your code, changed Fill to FillNew to separate it for now, and tried FillNew(new A()), and it said it can't convert A to System.Func<A>.
(the
.Invoke()
is a bit more verbose than necessary, factory()
will work)u would either have to pass a lambda expression
() => new A()
or pass a method:
tbh i usually dont use the short version because it sorta feels wrong reading that, u could call the parameter create
or createInstance
and call it the short way, but then the parameter name feels weird. personal opinion ;pThis compiled:
map.FillNew(() => new A());
Not much luck with the InstanceMethod one.can u show how u tried it with the instance method?
and the error itself ;p
map.FillNew(A.InstanceMethod());
And Cannot convert from 'A' to 'System.Func<A>'
Oh, I changed A.InstanceMethod() to A.InstanceMethod and it worked.u r trying to execute the method, not passing the method
Parenthesis felt natural 🙂
I see.
yeah, no ;p
also, ur
InstanceMethod
is a static method, not an instance one ;p
instance method -> an instance for the method (this
) exists.
static method -> is bound to the type itself, an instance does not existThe alternative would have been this, which seemed odd to create a new instance.
well u could have done something like
basically to vary some values, or even give it more complex logic
I see. I don't think I want a general factory class for every game class though (Wall, Floor, Cat, etc.). That can get big for my game with several CreateInstance's of each class. But at least I know several ways of doing it, and it depends on what I need of course. I'll be using all of these, I'm sure. Thanks for the help!
ignore the following if its too overwhelming:
u could create a factory method factory class xD
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.