C# issue with class instantiation - class

I'm running a C# project on VS2019 with the following code structure:
In the Class1.cs file:
public class Class1
{
public class MyClass2 : Class2
{
...
}
private void RunAlgorithm<T>() where T : Class2, new()
{
T argInstance = new T();
...
}
static void Main(string[] args)
{
RunAlgorithm<MyClass2>();
}
}
In the Class2.cs file:
public class Class2
{
public Class2() { }
public string setParameters { get; set; }
}
I'm getting the following error for the line RunAlgorithm<MyClass2>();
'Class1.MyClass2' must be a non-abstract type with a public
parameterless constructor in order to use it as parameter 'T' in the
generic type or method 'Class1.RunAlgorithm()'

even if I change it to Public, the error persists
Well, minimally, it'll have to be protected so that MyClass can access it..
https://dotnetfiddle.net/XFeEdQ
public class Class1
{
class MyClass2 : Class2
{
}
private void RunAlgorithm<T>() where T : Class2, new()
{
T argInstance = new T();
}
public static void Main(string[] args)
{
new Class1().RunAlgorithm<MyClass2>();
}
}
public class Class2
{
protected Class2() { }
public string setParameters { get; set; }
}
So your "Class1.MyClass2
must have a public parameterless constructor" message is saying that your MyClass needs a constructor. Mine above has such a constructor even though it's not in the code; in the absence of the developer providing a constructor the compiler provides one that does nothing other than call the base parameterless constructor...
...which leads me to the next point; your MyClass2 extends Class2, and hence Class2's constructor needs to be accessible to it. While Class2's constructor is private, MyClass2's constructor can't call it. Every constructor on c# has to either call another constructor or a base constructor. If you don't specify which, the compiler will insert a call to base() for you, which will fail if the base constructor is inaccessible
For this all to work out you need a public parameterless constructor in MyClass2:
public MyClass2():base(){}
or without the base(compiler will add the base call)
or blank (compiler will add all of it)
and you need something that makes Class2's constructor accessible to MyClass2, ie declaring Class2's constructor as public or protected

Related

Java program compilation failed

While studying interface I came along this weird behaviour
When I am running this
int num=20;
public void sound();
public void eat();
}
class Dog implements Animal{
public void sound(){
System.out.println("Wooof!!!!!!!");
}
public void eat(){
System.out.println("Food");
}
}
public class Main{
public static void main(String[]args){
Dog dog=new Dog();
dog.sound();
dog.eat();
System.out.println(Dog.num);
//System.out.println(Dog.num1);
}
}
It runs fine while If I declare a no static variable with same name i.e. num as of the one in interface like this
interface Animal{
int num=20;
public void sound();
public void eat();
}
class Dog implements Animal{
int num=10;
public void sound(){
System.out.println("Wooof!!!!!!!");
}
public void eat(){
System.out.println("Food");
}
}
public class Main{
public static void main(String[]args){
Dog dog=new Dog();
dog.sound();
dog.eat();
System.out.println(Dog.num);
//System.out.println(Dog.num1);
}
}
It gives this error Main.java:22: error: non-static variable num cannot be referenced from a static context
My question was since one from interface is static and is of class level why the child class i.e. Dog compilation fails when I declare a non static instance level variable.
The problem is your are trying to access Dog class into System.out.println(). Not the variable dog where the class has been initialized.
If variable num is not static is impossible to read it without initialize the class, so if you want to do Dog.num, that variable has to be static.
If you don't add the variable into Dog class, the value will be declared in the interface, but if the variable exists in the class, the compiler will try read that.

Autofac - One interface, multiple implementations

Single interface: IDoSomething {...}
Two classes implement that interface:
ClassA : IDoSomething {...}
ClassB : IDoSomething {...}
One class uses any of those classes.
public class DummyClass(IDoSomething doSomething) {...}
code without Autofac:
{
....
IDoSomething myProperty;
if (type == "A")
myProperty = new DummyClass (new ClassA());
else
myProperty = new DummyClass (new ClassB());
myProperty.CallSomeMethod();
....
}
Is it possible to implement something like that using Autofac?
Thanks in advance,
What you are looking for is, as I remember, the Strategy Pattern. You may have N implementations of a single interface. As long you register them all, Autofac or any other DI framework should provide them all.
One of the options would be to create a declaration of the property with private setter or only getter inside Interface then implement that property in each of the class. In the class where you need to select the correct implementation, the constructor should have the parameter IEnumerable<ICommon>.
Autofac or any other DI frameworks should inject all possible implementation. After that, you could spin foreach and search for the desired property.
It may look something like this.
public interface ICommon{
string Identifier{get;}
void commonAction();
}
public class A: ICommon{
public string Identifier { get{return "ClassA";} }
public void commonAction()
{
Console.WriteLine("ClassA");
}
}
public class A: ICommon{
public string Identifier { get{return "ClassB";} }
public void commonAction()
{
Console.WriteLine("ClassA");
}
}
public class Action{
private IEnumerable<ICommon> _common;
public Action(IEnumerable<ICommon> common){
_common = common;
}
public void SelectorMethod(){
foreach(var classes in _common){
if(classes.Identifier == "ClassA"){
classes.commonAction();
}
}
}
}

GWT RPC serializing

I am trying to send over MyClass through RPC, but am getting :
Type MyClass was not assignable to 'com.google.gwt.user.client.rpc.IsSerializable' and did not have a custom field serializer.For security purposes, this type will not be serialized.
I have looked at GWT - occasional com.google.gwt.user.client.rpc.SerializationException and tried their solution, but it did not work.
The difference is that MyClass is located in another project.
The project structure is:
MyApiProject
-contains MyClass
MyClientProject
MyServerProject
I have also tried passing an enum through the RPC from MyApiProject, which also failed.
public class MyClass
implements Serializable
{
private static final long serialVersionUID = 5258129039653904120L;
private String str;
private MyClass()
{
}
public MyClass(String str)
{
this.str = str;
}
public String getString()
{
return this.str;
}
}
in the RemoteService I have:
mypackage.MyClass getMyClass();
in the RemoteServiceAsync I have:
void getMyClass(AsyncCallback<mypackage.MyClass> callback);
I had to change implements Serializable to implements IsSerializable
This usually pops up when you are using another type inside of your class that is not serializable. Check the properties of your class and make sure they are all serializable, post the code of MyClass here and I can look at it as well.
I believe GWT requires an RPC serializable class to also have a public no-argument constructor.
Try removing
private MyClass()
{
}
or set it to
public MyClass()
{
}

MEF Error when add item to list in constructor method

i write silverlight program very simple.i use Mef and WCF.
this code is MainPageViewModel class that included Commands and properties.
public List<NoOfStudentsDropDownItem> ListNoOfStudent{get;set;}
public MainPageViewModel()
{
InitializList();
}
private void InitializList()
{
ListNoOfStudent.Add(New NoOfStudentsDropDownItem(){DisplayText="1",NoOfStudent=-1});
ListNoOfStudent.Add(New NoOfStudentsDropDownItem(){DisplayText="5",NoOfStudent=5});
}
this is NoOfStudentsDropDownItem class;
public Class NoOfStudentsDropDownItem
{
public string DisplayText{get;set;}
public int NoofStudent{get;set}
}
this is part of App Class.
private void Application_Startup(object sender,StartupEventArgs e)
{
CompositionInitializer.SatisfyImports(this);
MainPage mainpage=new MainPage();
mainpage.DataContext=MainViewModel;
this.RootVisual=mainpage;
}
[Import]
public MainPageViewModel MainViewModel{get;set;}
i haven't error when commented InitializList method.i dont know cause.
You simply forgot to create the list. You declared a property for it, but it is never assigned so it will still be null when you call Add.

How to get Castle Windsor to call parameterless constructor?

Currently I have a class that looks like this:
public class MyClass : IMyClass
{
public MyClass()
{
//...
}
public MyClass(IMyRepository repository)
{
//...
}
}
In my config file I have IMyClass registered, but not IMyRepository. My intention is for Windsor to use the constructor that doesn't take any parameters, but I am getting this message:
Can't create component 'MyClass' as it
has dependencies to be satisified.
MyClass is waiting for the following
dependencies:
Services:
- Namespace.IMyRepository which was not registered.
I found another post that says that the container will call the constructor with the most arguments that it can satisfy. So why is it trying to call the constructor with an argument that it doesn't know how to satisfy?
Maybe you're using an old version of Windsor... this works just fine for me:
[TestFixture]
public class WindsorTests {
public interface ISomeInterface {}
public class AService {
public int Id { get; private set; }
public AService() {
Id = 1;
}
public AService(ISomeInterface s) {
Id = 2;
}
}
[Test]
public void Parameters() {
var container = new WindsorContainer();
container.AddComponent<AService>();
var service = container.Resolve<AService>();
Assert.AreEqual(1, service.Id);
}
}