Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use classes themselves as method parameters?

Tags:

methods

c#

class

Its been a while but i need to convert some custom code into C# (i think it was called emeralds or something somebody else gave to me). there is a certain method that takes a class(any class without any object conversions). this is the code im trying to convert.

      class  management
        Accessor current_class
        Accessor class_Stack

      def call(next_class)          #method, called global, takes a "class" instead 
                                       #of a variable, kinda odd
        stack.push(current_class)      #stack handling
        current_class = next_class.new #makes a new instance of specified next_class

      end
    end

next_class seems to be any class related to a base class and assigns a new instance of them to a variable called currentClass. there are other "methods" that do something similar. I've tried setting the parameter type to "object", but loses all the the "next_class" attributes that are needed. this is my attempt at it

     public class management {
        public Stack stack;           
        public Someclass currentClass; 

      public void Call(object nextClass) {
        stack.push(currentClass);   // stack handling    
        currentClass = new nextClass(); // conversion exception, otherwise loss of type

    }
    }

IS this even possible in C# another thing this language seems to able to keep attributes(methods too) from Child classes when you cast them as a base class. e.g cast green bikes as just bikes but it will still be green

can somebody point me in the right direction here? or do i need to rewrite it and change the way it does things?

like image 225
Fornoreason1000 Avatar asked Mar 24 '23 05:03

Fornoreason1000


1 Answers

What you want is Generics and I think also, based on the fact that you call a method, Interfaces.

So your Interface will define "new" and the Class will inherit from the interface.

You can then pass the class as a generic and call the Interface method of "new" on it.

So;

public interface IMyInterface
{
  void newMethod();
}

public class MyClass1 : IMyInterface
{
    public void newMethod()
    {
      //Do what the method says it will do.
    }
}

public class Class1
{
    public Class1()
    {
        MyClass1 classToSend = new MyClass1();
        test<IMyInterface>(classToSend);
    }

    public void test<T>(T MyClass) where T : IMyInterface
    {
        MyClass.newMethod();
    }
}

EDIT

And check out "dynamic" in C# 4.0. I say this because if you don't know what the method is until runtime you can define it as dynamic and you are basically telling the compiler that "trust me the method will be there".

This is in case you can't use generics because the methods you call will be different for each class.

like image 104
griegs Avatar answered Apr 02 '23 09:04

griegs