Make instance of "object" to other class and call method - c#

I want to define an object and make instance of it to other class, but I can't call the method, here's my code:
class Test1
{
public bool True_1()
{return true;}
}
class Test2
{
public bool True_2()
{return true;}
}
class MainClass
{
static void Main()
{
object a;
bool flag = true; // or false
if (flag)
a = new Test1();
else
a = new Test2();
if (a is Test1)
a.True_1(); //error before compiling
else
a.True_2(); //error before compiling
}
}
}
I know there's a way of creat an interface I_Test, and do this:
class Test1:I_Test
class Test2:I_Test
but since class Test2 is a dll from third-party so I can't add :I_Test to it,
so I want to make my code here achievable, any suggestion? thx!

If you are using the C# 7 you can use the new syntax that allows you to test and put the result of the test into a variable in a single line :
if (a is Test1 aTest)
aTest.True_1();
else if( a is Test2 aTest2)
aTest2.True_2();
If you are using older C# you can use the as operator coupled with a null test :
var aTest = a as Test1;
if (aTest != null)
aTest.True_1();
else
{
var aTest2 = a as Test2;
if (aTest2 != null)
{
aTest2.True_2();
}
}
You can also use a test and cast solution which minimizes the amount of variables, this is not recommended as that may forces the runtime to test twice (once for is and once for the cast). See this question for a more detailed response
if(a is Test1)
((Test1)a).True_1();

You can do these two solutions to solve this problem:
1. Convert a to the class that you want and then you can call the method: Try this:
static void Main()
{
object a;
bool flag = true;
if (flag)
a = new Test1();
else
a = new Test2();
if (a is Test1)
{
((Test1)a).True_1(); //So, there will be no error anymore
}
else
{
((Test2)a).True_2();
}
}
use dynamic keyword instead of object type. Try this:
static void Main()
{
dynamic a;
bool flag = true;
if (flag)
a = new Test1();
else
a = new Test2();
if (a is Test1)
a.True_1(); //So, there will be no error anymore
else
a.True_2();
}

You have to cast it first
if(a is Test1 aConverted)
aConverted.True_1();
Or older way of doing this:
if(a is Test1)
((Test1)a).True_1();

Let's say you have a third party DLL that contains a class...
class ThirdPartyClass
{
public bool Foo { get { return true;} }
}
And you want to create your own class that has a method or property in common with the third party class:
class MyClass
{
public bool Foo { get { return true;} }
}
As you mention, what you'd normally do is add an interface to the third party class, and then implement that interface in your own class. But you can't do that, as you also pointed out. And without an interface in common, you're stuck with that clunky if/then construct.
If I correctly understand your situation, you can deal with it as follow. Extend the third party class to add the interface, like so:
interface IMyInterface
{
bool Foo { get; }
}
class MyThirdPartyClass : ThirdPartyClass, IMyInterface
{
}
Since Foo is public, it will get inherited and be available, and satisfy the interface. And now you can create your own class too:
class MyClass : IMyInterface
{
public bool Foo { get { return true; }}
}
And you can use them interchangeably:
IMyInterface a = new MyThirdPartyClass();
IMyInterface b = new MyClass();
bool c = a.Foo;
bool d = b.Foo;
That's how I would do it.
You may run into a problem if the third party class is sealed. If that is the case, you have to wrap it instead of inheriting from it:
class MyThirdPartyClassWrapper : IMyInterface
{
private readonly ThirdPartyClass _wrappedInstance = new ThirdPartyClass();
public bool Foo { get { return _wrappedInstance.Foo; } }
}
And then it'll still work:
IMyInterface a = new MyThirdPartyClassWrapper();
IMyInterface b = new MyClass();
bool c = a.Foo;
bool d = b.Foo;

Related

Moq parent method being called in child class

I have a base class with a protected method that's being called in a public method in the child class I want to test. I'm failing to find a way to moq the base protected method for easier testing in child class.
public class MyBaseClass
{
protected virtual bool MyMethod(int number)
{
return number == 1;
}
}
public class MyChildClass : MyBaseClass
{
public bool DoSomething(int number)
{
return MyMethod(number);
}
}
[TestFixture]
public class MyChildClassTests
{
[Test]
public void Expected_Returns_False_WhenPassed_1()
{
var myChildClass = new MyChildClass();
// How do I mock MyMethod used in myBaseClass here?
// var mock = new Mock<MyBaseClass>();
// mock.Protected().Setup<bool>("MyMethod", ItExpr.IsAny<int>()).Returns(false);
// The above mock is correct, but it's in a different instance object than myBaseClass
var result = myChildClass.DoSomething();
Assert.AreEqual(false, result);
}
}
I can't change the classes to have a better architecture and I must do the best I can to implement unit test for DoSomething(), what I did so far is mock and prepare all the data that method uses, but since it's in another class I'd love my MyChildClassTests to not do all that and just limit to test DoSomething().
I've read about partial mocking and a whole lot of other questions and answers and I can't get it to work right.
I appreciate any suggestions!
Edit: Forgot to put public in all the classes, in my real world case, they are public.
class MyChildClassTests
{
[Test]
public void Expected_Returns_False_WhenPassed_1()
{
var myChildClass = new FakeChildClass();
var result = myChildClass.DoSomething(1);
Assert.AreEqual(false, result);
}
}
public class FakeChildClass: MyChildClass
{
protected override bool MyMethod(int number)
{
return number == 1;
}
}
First of all, ensure your classes are public.
Moq will complain about not being able to proxy into them if they're not.
public class MyBaseClass
{
public virtual bool MyMethod(int number)
{
return number == 1;
}
}
public class MyChildClass : MyBaseClass
{
public bool DoSomething(int number)
{
return MyMethod(number);
}
}
Next, make your base class method public. You won't be able to set it up unless you do.
After that, create a mock of the child object and mock the parent method.
var mockChild = new Mock<MyChildClass>(){CallBase = true};
mockChild.Setup(x => x.MyMethod(It.IsAny<int>())).Returns(false);
Pull your result.... result will return false even though the actual implementation would have returned true with 1 as a parameter.
var result = mockChild.Object.DoSomething(1);
When calling the DoSomething method, you'll actually enter the real implementation of that (put a breakpoint on if you don't believe me!) - but the mocked version of MyMethod will kick in.
Thanks all for your replies, gathering all I was able to get the actual answer to my use case:
Without changing MyBaseClass and MyChildClass:
public class MyBaseClass
{
protected virtual bool MyMethod(int number)
{
return number == 1;
}
}
public class MyChildClass : MyBaseClass
{
public bool DoSomething(int number)
{
return MyMethod(number);
}
}
I was able to mock the protected method and save me a LOT of work and duplicate code (that was in MyBaseClassTests already)
[TestFixture]
public class MyChildClassTests
{
[Test]
public void Expected_Returns_False_WhenPassed_1()
{
var expected = false;
var myChildClass = new Mock<MyChildClass> {CallBase = true};
myChildClass.Protected().Setup<bool>("MyMethod", 1).Returns(expected);
var result = myChildClass.Object.DoSomething(1);
Assert.AreEqual(expected, result);
}
[Test]
public void Expected_Returns_True_WhenPassed_1()
{
var expected = true;
var myChildClass = new Mock<MyChildClass> {CallBase = true};
myChildClass.Protected().Setup<bool>("MyMethod", 1).Returns(expected);
var result = myChildClass.Object.DoSomething(1);
Assert.AreEqual(expected, result);
}
}
Thanks everyone for your help! :)

How to find if my Action<T> is already in list List<Action<T>> [duplicate]

I'm building a hierarchical collection class that orders magnetic resonance images spatially and arranges them into groupings based on the various acquisition parameters that were used to generate them. The specific method used to perform the grouping is provided by the user of the class. I've abstracted out the relevant features in the sample code below. For the IEquatable<MyClass> implementation, I'd like to be able to compare the _myHelperDelegate attributes of two MyClass instances to determine if both delegates point to the same piece of code. The (_myHelperDelegate == other._myHelperDelegate) clause in the if statement below is clearly the wrong way to go about doing this (it fails to compile, giving the error "Method name expected"). My question is, is there a way to compare two delegates to determine if they reference the same piece of code? If so, how do you do that?
public class MyClass : IEquatable<MyClass>
{
public delegate object HelperDelegate(args);
protected internal HelperDelegate _myHelperDelegate;
public MyClass(HelperDelegate helper)
{
...
_myHelperDelegate = helper;
}
public bool Equals(MyClass other)
{
if (
(_myHelperDelegate == other._myHelperDelegate) &&
(... various other comparison criteria for equality of two class instances... )
)
return true;
return false;
}
}
The following compiles and works as expected.
private void Form1_Load(object sender, EventArgs e)
{
var helper1 = new TestDelegates.Form1.MyClass.HelperDelegate(Testing);
var helper2 = new TestDelegates.Form1.MyClass.HelperDelegate(Testing2);
var myClass1 = new MyClass(helper1);
var myClass2 = new MyClass(helper1);
System.Diagnostics.Debug.Print(myClass1.Equals(myClass2).ToString()); //true
myClass2 = new MyClass(helper2);
System.Diagnostics.Debug.Print(myClass1.Equals(myClass2).ToString()); //false
}
private object Testing()
{
return new object();
}
private object Testing2()
{
return new object();
}
public class MyClass : IEquatable<MyClass>
{
public delegate object HelperDelegate();
protected internal HelperDelegate _myHelperDelegate;
public MyClass(HelperDelegate helper)
{
_myHelperDelegate = helper;
}
public bool Equals(MyClass other)
{
if (_myHelperDelegate == other._myHelperDelegate)
{
return true;
}
return false;
}
}
Per msdn, Delegate.Equals method returns:
true if obj and the current delegate have the same targets, methods, and invocation list; otherwise, false.
Have you tried this?
Old question, but I wrote a simple example program to demonstrate comparing delegates with Delegate.Equals -
public delegate int test1(int t);
public static int asdf(int t)
{
return t + 5;
}
public static int asdf2(int x)
{
return x + 7;
}
public static void CompareDelegates(test1 test1, test1 test2)
{
Console.WriteLine(test1 == test2);
}
public static void Main(string[] args)
{
test1 test1 = asdf;
test1 test2 = asdf2;
test1 test3 = asdf;
CompareDelegates(test1, test1);
CompareDelegates(test1, test2);
CompareDelegates(test2, test3);
CompareDelegates(test1, test3);
}
// Outputs:
//
// True
// False
// False
// True

Unity3D C# abstract class with static instance creation not working

Hello I am working on a objectpooling class has T "ObjectPooling".
And made a child class. So I want to make automatic singleton for this class. So if I use "instance" it should check if m_instance is null. If yes "spawn" the script and assign m_instance.
public abstract class ObjectPooling<T> : MonoBehaviour
{
public static float start = 30;
public static bool extendable = true;
public List<T> objects = new List<T>();
public abstract T getNext();
public abstract void Add(T obj);
static T m_instance;
public static T instance
{
get
{
return m_instance ?? (m_instance = CreateInstance());
}
}
protected static T CreateInstance()
{
GameObject g = new GameObject("ObjectPooling");
var c = g.AddComponent<T>();
return c;
}
}
The problem is at the last lines in the CreateInstance().
It says
An implicitly typed local variable declaration cannot be initialized
with `UnityEngine.GameObject.AddComponent(System.Type)'
I am not sure what can I do here now. I tried with ObjectPooling before but thats gives no error but also is not working.
So my goal is that the child has also singleton. I did it currently manually but want I want to later should be like this (ofc the base class should do it instead of child class but still check it).
public class BulletPooling : ObjectPooling<BulletBase>
{
public override void Add(BulletBase obj)
{
if(extendable)
objects.Add(obj);
}
public override BulletBase getNext()
{
for(int i = 0; i < objects.Count; i++)
{
var bs = objects[i];
if (!bs.gameObject.activeInHierarchy)
return bs;
}
return null;
}
// this part
static BulletPooling m_instance;
public static BulletPooling instance
{
get
{
return m_instance ?? (m_instance = CreateInstance());
}
}
protected static BulletPooling CreateInstance()
{
GameObject g = new GameObject("ObjectPooling");
var c = g.AddComponent<BulletPooling>();
return c;
}
}
You can see here I am working with new Childclass which has T = BulletBase
This is because GameObject.AddComponent requires an object of a specific type, rather than "any type". In your ObjectPooling class, you only specify that it can be an object of any type, and the compiler cannot infer which types you are using beforehand.
AddComponent is kind of a nasty function, since you can also pass it a string, which should be the name of a script class.
You could specify the type that T must adhere to as UnityEngine.Component to get around this. that would look like this :
public abstract class ObjectPooling<T>: MonoBehaviour where T : UnityEngine.Component
{
public static float start = 30;
public static bool extendable = true;
public List<T> objects = new List<T>();
public abstract T getNext();
public abstract void Add(T obj);
static T m_instance;
public static T instance
{
get
{
return m_instance ?? (m_instance = CreateInstance());
}
}
protected static T CreateInstance()
{
GameObject g = new GameObject("ObjectPooling");
//this is where your compiler could not tell if T was the correct type by the way...
var c = g.AddComponent<T>();
return c;
}
}
but that might break the functionality of adding scripts as game components using a string with their name. (though i think in your case, it won't be a problem)

Returning an unknown object

As an example, I have a base class called baseAbstractClass and a couple of derived classes:
public class Derived : baseAbstractClass
{
public Derived()
{
}
// abstract methods go here
}
public class DerivedEx : baseAbstractClass
{
// code goes here
}
and I have this class:
public class SomeClass
{
public SomeClass()
{
}
object ReturnMeAnObject(int whichObject)
{
object toReturn = null;
if (whichObject == 0)
{
toReturn = new Derived();
}
else
if (whichObject == 1)
{
toReturn = new DerivedEx();
}
return toReturn;
}
}
In my Main function:
public class Start
{
static void Main()
{
SomeClass someClass = new SomeClass()
Derived derived = (Derived)someClass.ReturnMeAnObject(0);
}
}
The object that I'm returning is unknown until runtime, but in reality I don't know the type of object is going to be returned - It could be Derived, or DerivedEx.
Is there a simplier way than having to cast my return value as shown in the Main function as this can result in a very large switch statement or, a very large set of If... Else conditions.
I have tried to determine if my design is correct by constructing a class diagram, but can't seem to fit it into code.
Any help would be greatly appreciated.
Your problem can be solved using generics. You have to limit the generic parameter T and ensure that the class that is used has a default constructor.
public T ReturnMeAnObject<T>() where T : baseAbstractClass, new()
{
return new T();
}
Then you can use this in your code as follows:
SomeClass someClass = new SomeClass()
Derived derived = someClass.ReturnMeAnObject<Derived>();
DerivedEx derivedEx = someClass.ReturnMeAnObject<DerivedEx>();
You can also use the Reflection class. like:
object derived = someClass.ReturnMeAnObject(0);
Type t = derived.GetType();
switch (t.Name)
{
case "Derived":
//do something
break;
case "DerivedEx":
//do something
break;
default:
break;
}
You can use Polymorphism here and return base class object :
baseAbstractClass ReturnMeAnObject(int whichObject)
{
baseAbstractClass toReturn = null;
if (whichObject == 0)
{
toReturn = new Derived();
}
else
if (whichObject == 1)
{
toReturn = new DerivedEx();
}
return toReturn;
}
and you can test it :
SomeClass someClass = new SomeClass();
var derived = someClass.ReturnMeAnObject(0);
var DerviedTyped = Convert.ChangeType(derived,derived.GetType());
EXAMPLE FIDDLE
UPDATE:
you can cast it dynamically using Convert.ChangeType() :
SomeClass someClass = new SomeClass();
var derived = someClass.ReturnMeAnObject(0);
var derviedTypedObject = Convert.ChangeType(derived,derived.GetType());

How to prevent an instantiation of an object in c#

What I need is to check the parameters passed to the constructor and prevent the instantiation of the specific object in case they are treated as invalid.
What I have found is that an exception can be thrown so the object reference will end up with "null" as expected.
For example, this class will be instantiated only if the integer passed to the constructor is non negative.
class MyClass
{
public MyClass(int a)
{
if (a < 0)
{
throw new Exception();
}
}
}
Although the above works fine, I bet that c# can provide a cleaner way to do this, avoiding the extra cost of the try/catch need, each time a new object is about to be constructed.
static void Main(string[] args)
{
MyClass e1;
MyClass e2;
try
{
e1 = new MyClass(1);
}
catch(Exception) { }
try
{
e2 = new MyClass(-1);
}
catch(Exception) { }
}
In cases like this, you should consider using the Factory Pattern. You made the constructor private, and instead use a static method to return an instance.
public class Foo {
private Foo(int a) { ... }
public static Foo GetFoo(int a) {
if (a < 0) {
throw new Exception("No Foo for you!");
// or
return null;
}
return new Foo(a);
}
}
public class Program {
public static void Main() {
Foo f;
f = new Foo(); // Not allowed, ctor is private.
f = Foo.GetFoo(42); // Do this instead.
}
}
With this, you can do some pretty interesting stuff.
Here, we have a Foo class, with different sub-classes. By using the Factory Pattern, we can construct an instance of a particular Foo sub-class, without the outside world even knowing that any subclasses exist!
public abstract class Foo {
// Private implementations of Foo
// No one outside can ever construct one directly.
private class RedFoo : Foo { }
private class GreenFoo : Foo { }
private class BlueFoo : Foo { }
public static Foo GetColoredFoo(string color) {
switch (color.ToLower()) {
case "red": return new RedFoo();
case "green": return new GreenFoo();
case "blue": return new BlueFoo();
}
throw new Exception("No Foo for that color!");
}
}
public class Program {
public static void Main() {
Foo f;
f = new Foo(); // Not allowed; Foo is abstract
f = new RedFoo(); // Not allowed, RedFoo is private, inside of Foo
f = Foo.GetColoredFoo("red"); // Returns an instance of RedFoo
}
}
This moves the knowledge of "how to best construct the object you really need" into the definition of the class itself, and of course eliminates the try/catch. You could apply any logic you need inside of the static factory method.
You can go with the factory pattern, as suggested by MarcinJruaszek, by making the constructor private and add a static method:
public class myClass
{
private myClass(int a)
{
// constructor
}
public static myClass Create(int a){
if (a < 0)
{
return null;
}
return new myClass(a);
}
}
And do myClass.Create(1).
What I suggest you do is create a static method of your class that accepts the parameters you need to verify and have that return the object. I do not know of a way to abandon object creation during a constructor without throwing an Exception.

Categories