Problem converting array of struct from C++ to C# - c#

I want to convert this C++ code to C#:
typedef struct consoleCommand_s
{
char* cmd ;
void (*function)() ;
} consoleCommand_t ;
static consoleCommand_t commands[] =
{
{"clientlist", &CG__Clientlist},
{"say", &CG_Say},
{"nick", &CG_Nick},
{"logout", &CG_Logout}
} ;
// e.g.
static void CG_Logout(void)
{
// Logout
}
The closest i have come is this:
public class Class1
{
// public delegate int Calculate (int value1, int value2);
public delegate void fnCommand_t();
public class consoleCommand_t
{
public string strCommandName;
public fnCommand_t fnCommand;
public consoleCommand_t(string x, fnCommand_t y)
{
this.strCommandName = x;
this.fnCommand = y;
} // End Constructor
} // End Class consoleCommand_t
public static void Nick()
{
Console.WriteLine("Changing Nick");
} // End Sub
public static void Logout()
{
Console.WriteLine("Logging out");
} // End Sub
// string[] names = new string[] {"Matt", "Joanne", "Robert"};
public consoleCommand_t[] commands = new consoleCommand_t[] {
new consoleCommand_t("Nick", Nick),
new consoleCommand_t("Logout", Logout)
};
} // End Class Class1
Now I wanted to ask:
A) Why does Nick & Logout need to be static when all the rest is not ?
B) Is there no C-like way to initialize the commands array, that is, without new ?

You could do without having a class INSIDE another class and manage your default console commands in another.
public delegate void ConsoleCmd();
public class DefaultCommands
{
public static void Nick()
{
Console.WriteLine("I'm Nick!");
}
public static void LogOut()
{
Console.WriteLine("You're Fired!");
}
}
public class Console
{
private Dictionary<string, ConsoleCmd> mCommands;
public Console()
{
mCommands = new Dictionary<string, ConsoleCmd>();
mCommands.Add("Nick", DefaultCommands.Nick);
mCommands.Add("Logout", DefaultCommands.LogOut);
}
}
Accessing your commands would be as easy as:
ConsoleCmd command = mCommands["Nick"];
command();
EDIT: Failed to mention this. This is to point to the OP that there are other better methods to achieve what he wants to do. And probably doesn't answer his question but I hope will point him to the right direction in terms of his switch from functional programming language to purely object-oriented language.

Nick & Logout may be non-static:
public void Nick(){}
public void Logout(){}
public consoleCommand_t[] commands = new consoleCommand_t[] {
new consoleCommand_t("Nick", this.Nick),
new consoleCommand_t("Logout", this.Logout)
};

B) Is there no C-like way to initialize the commands array, that is, without new ?
Don't get hung up on the new keyword in C#, it's just how initialisation is written. In C#, the analagous distinction between stack allocation and heap allocation is made using struct vs class. (So you might like to make your ConsoleCommand_t a struct.)
Edit: And with a struct you can also do:
new consoleCommand_t() {strCommandName = "Nick", fnCommand = Nick}
And skip writing the consoleCommand_t constructor. That's about as close as you can get to your C-style struct initialization, I think

Related

Modifying static value variables by reference in a new object

I'm trying to modify a bunch of static value variables as fields in a static class. They need to be initialized in some sort of structure with a string attached to them, but the outside world should be able to just get the variable directly.
Here's a basic code dump of what I'm trying to do (disregard the specifics inside of DoStuff(); just an example of the kind of operations I'm trying to do):
public unsafe static class StaticVariables
{
public static int foo;
public static int bar;
...
public static int bazinga;
static IEnumerable<StaticInteger> intList = new List<StaticInteger>
{
new StaticInteger(&foo,"foo"),
new StaticInteger(&bar,"bar"),
...
new StaticInteger(&bazinga,"bazinga")
};
public static void DoStuff()
{
foreach(StaticInteger integer in intList)
{
if(integer.identifier=="foo") *integer.pValue = 30;
if (integer.identifier == "bar") *integer.pValue = 23;
}
Console.WriteLine("{0} {1}", foo, bar);
}
}
public unsafe class StaticInteger
{
public int* pValue;
public string identifier;
public StaticInteger(int* pValue, string identifier)
{
this.pValue = pValue;
this.identifier = identifier;
}
}
I'm not able to grab the address of foo/bar where I want to. They're static/globals, so they shouldn't going anywhere. I can cheat and use fixed inside of DoStuff to initialize the list, but I want to be able to reference my list multiple times after initialization, and I'm not sure that's safe because we'd no longer be in the fixed block. Is there a way to tell the GC "Don't touch where you put this static variable please"?
I'd be super happy if the answer was "don't use pointers, do XYZ instead."
Using a properties with only a getter rather than fields you can limit users to only reading values & the values can be stored in a Dictionary rather than a list.
public static class StaticVariables
{
public static int foo { get {return values["foo"];}}
public static int bar { get {return values["bar"];}}
public static int bazinga { get {return values["bazinga"];}}
private static Dictionary<String,int> values = new Dictionary<String,int>();
static StaticVariables()
{
values.Add("foo",0);
values.Add("bar",0);
values.Add("bazinga",0);
}
public static void DoStuff()
{
values["foo"] =30;
values["bar"] =23;
}
}

Does java support explicit interface implementation like c#? [duplicate]

This question already has answers here:
Is the C# "explicit implementation" of the interface present in Java?
(4 answers)
Closed 9 years ago.
i tried doing this :
interface pet {
void sleep();
}
interface robot {
void sleep();
}
public class roboGarfield implements pet , robot {
/*
* this gives error
void pet.sleep(){
}
*/
#Override
public void sleep() { System.out.println("this isn't really specific.."); }
public static void main(String[] args){
roboGarfield t = new roboGarfield();
t.sleep();
((pet)t).sleep(); // similar to C#
((robot)t).sleep();
}
}
But even though i can cast the roboGarfeild object to its pet or robot type , i cant do an explicit implementation like c#.
Anything i'm doing wrong ? or is it just not supported in java ?
Edit: So , java doesn't support explicit interface implementation like C#. But for cases where they can't be avoided , Holger's delegate method seems like the way out.
Thanks for all the replies.
The standard solution to this kind of problem is to use delegation:
interface pet {
void sleep();
}
interface robot {
void sleep();
}
public class roboGarfield {
private final pet myPetIdentity = new pet() {
public void sleep() { System.out.println("sleeping as pet"); }
public String toString() { return roboGarfield.this.toString(); };
};
private final robot myRobotIdentity = new robot() {
public void sleep() { System.out.println("recharging as robot"); }
public String toString() { return roboGarfield.this.toString(); };
};
public final pet asPet() {
return myPetIdentity;
}
public final robot asRobot() {
return myRobotIdentity;
}
public static void main(String[] args){
roboGarfield t = new roboGarfield();
t.asPet().sleep();
t.asRobot().sleep();
}
}
For bigger methods it’s recommended to let the inner classes delegate back to the outer class to keep the inner classes short. Further, subclasses could override these methods without dealing with the delegation stuff then.
public class roboGarfield {
private final pet myPetIdentity = new pet() {
public void sleep() { petSleep(); }
public String toString() { return roboGarfield.this.toString(); };
};
private final robot myRobotIdentity = new robot() {
public void sleep() { roboSleep(); }
public String toString() { return roboGarfield.this.toString(); };
};
public void roboSleep()
{
System.out.println("recharging as robot");
}
public void petSleep()
{
System.out.println("sleeping as pet");
}
public final pet asPet() {
return myPetIdentity;
}
public final robot asRobot() {
return myRobotIdentity;
}
public static void main(String[] args){
roboGarfield t = new roboGarfield();
t.asPet().sleep();
t.asRobot().sleep();
}
}
Java does not do that.
If two interfaces define methods of identical signature, there is no way to distinguish between them and you can only provide a single implementation that will be used by both.
You have to take care not to end up with interfaces that are incompatible that way.
public class roboGarfield implements pet , robot {
#ovveride
public void sleep(){
//here you are implementing sleep method
//But satisfying both pet and robot interface's sleep method.
}
When you do this , in java the single implementation works for the both interface. AFAIK, NO work around.

How to Avoid Assignment of Private Members in Constructor

I often find myself doing this:
class MyClass
{
public MyClass(int x)
{
this.x = x;
}
private int x;
...
}
Every time I add a new private member variable for configuration, I need to add it to the constructor's parameter list, to the constructor body, and to the class as a member. Is there a good programming pattern for avoiding the extra typing?
Generally speaking, If you instantiate a class with a bunch of private members that you have to pass into the constructor, you're doing something problematic already.
MyClass myClass = new MyClass(x, y, z, 7, 'c', someOtherClass)
If appropriate, you can encapsulate related fields into a struct or a different class like so
class MyClass
{
public MyClass(Coordinates coords)
{
this.coords = coords;
}
private Coordinates coords;
}
public struct Coordinates
{
public int X{get; set;}
public int Y{get; set;}
public int z{get; set;}
}
and then you can instanciate it with
MyClass myClass = new MyClass(new Coordinates() { X = 1, Y = 2, Z = 3 });
Without a particular implementation, It's kinda hard to determine the optimal solution, but if you don't actually have to set the fields from outside your class, you can do something like
class MyClass
{
public MyClass()
{
}
private int x = 2;
...
}
or
class MyClass
{
public MyClass()
{
this.x = 2;
}
private int x;
...
}
I find that I can abuse inheritance to accomplish my goal. I set up a "Loader" subclass that has the sole purpose in life of plugging in the dependencies of the base class. Then we can work with the base class and forget about the loader.
Then again, this has the horrible side-effect of preventing use of these protected member variables in the base constructor -- we need to use a .Start() function or something like that instead. So, this is a pretty bad solution, although saving some keystrokes.
public class MyClass
{
protected int param1;
protected int param2;
public void DoStuff()
{
Console.WriteLine(param1 + param2);
}
}
public class MyClassLoader : MyClass
{
public MyClassLoader()
{
param1 = 1;
param2 = 2;
}
}
class Program
{
static void Main(string[] args)
{
MyClass myObj = new MyClassLoader();
myObj.DoStuff();
Console.WriteLine("Press any key to quit.");
Console.ReadKey();
}
}

How do i change the call order of nested constructors (child before abstract parent)

The code below throws an exception because the abstract constructor is called before the child constructor.
I need to provide an abstract class to capsule some logic from a different part of the program. However i also need to check if the abstract members are initialised correctly rigth after creation without the childclass having any influence over this.
the compiling example below should illustrate my question.
using System;
namespace Stackoverflow
{
class Program
{
static void Main(string[] args)
{
var x = new Thing(5);
var y = new Child(x);
}
}
class Child : AbstractParent
{
Thing childthing;
public Child(Thing provided) : base(){
childthing = provided;
}
public override void Initialise(){
//Exception is thrown here - childthing is still null
parentthing = childthing.Add(1);
}
}
abstract class AbstractParent
{
protected Thing parentthing;
public AbstractParent(){
Initialise();
AssertThingyNotNull();
}
private void AssertThingyNotNull(){
if (parentthing == null) throw new Exception("Waaa");
}
public abstract void Initialise();
}
class Thing
{
private int i;
public Thing(int i){
this.i = i;
}
public Thing Add(int b){
i += b;
return new Thing(i);
}
}
}
Edit #1:
Is there some way to do this by reflecting into the caller (should be the creator of child rigth?) and then reacting on the end of that call?
Edit #2:
Getting the .ctor that creates the child is easy. Manipulating the methods seems something between impossible and a bad idea.
foreach (StackFrame frame in new StackTrace().GetFrames())
{
Console.WriteLine(frame.GetMethod().Name);
}
You can't, basically. This is why you should avoid calling virtual (or abstract) members from a constructor as far as possible - you could end up with code which is running with an incomplete context. Any variable initializers are executed before the base class constructor is called, but none of the code within the constructor body is.
If you need to perform initialization and only want to do that when the derived class constructor is running, then just call Initialise from the derived class constructor to start with.
You can do something similar to what Microsoft did with InitializeComponent()
then let the children call it whenever it can.
Try this.
Edited = cleaner version.
using System;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
var x = new Thing(5);
var y = new Child(x);
}
}
class Child : AbstractParent
{
public Child(Thing provided)
: base()
{
parentthing = provided;
base.Initialise();
}
}
abstract class AbstractParent
{
protected Thing parentthing;
public AbstractParent()
{
}
private void AssertThingyNotNull()
{
if (parentthing == null) throw new Exception("Waaa");
}
public void Initialise()
{
AssertThingyNotNull();
}
}
class Thing
{
private int i;
public Thing(int i)
{
this.i = i;
}
public Thing Add(int b)
{
i += b;
return new Thing(i);
}
}
}

read return value from delegate

I am not sure if I understood the usage of delegates correctly but I would like to read delegate return value in publisher class. The example is below with description.
//Publisher class
public class ValidateAbuse
{
public delegate List<String> GetAbuseList();
public static GetAbuseList Callback;
public void Ip(string ip)
{
// I would like to read GetAbuseList value (List<String>) here. How to do that?
}
}
//Subscriber class
class Server
{
public static void Start()
{
ValidateAbuse.Callback = GetIpAbuseList;
ValidateAbuse.Ip(MyIp);
}
private static List<string> GetIpAbuseList()
{
//return List<String> to ValidateAbuse class and use return value in public void Ip(string ip) method
}
public void Ip(string ip)
{
if (Callback != null)
{
List<String> valueReturnedByCallback = Callback();
}
}
Here's a version that does not use static for ValidateAbuse and that uses the built-in Func<T> delegate.
public class ValidateAbuse
{
private Func<List<string>> callback;
public ValidateAbuse(Func<List<string>> callback)
{
this.callback = callback;
}
public void Ip(string ip)
{
var result = callback();
}
}
public class Server
{
public static void Start()
{
var validateAbuse = new ValidateAbuse(GetIpAbuseList);
validateAbuse.Ip(MyIp);
}
private static List<string> GetIpAbuseList()
{
//return List<string> to ValidateAbuse class and use return value in public void Ip(string ip) method
}
}
I recommend you avoid static since that gives you a global state, which could later give you coupling problems and also makes it hard for you to unit test.
The other answers given so far has a guard clause, checking Callback for null. Unless that is expected behaviour (that Callback is null) I would avoid this. It's better to crash early than to get hard to debug errors later on.
I would also try to make the Server non-static.
It should be as simple as:
// Ip in your code sample is missing static
public static void Ip(string ip)
{
List<string> abuseList;
if (Callback != null)
abuseList = Callback()
}
However you can avoid creating a delegate all together by using a Func:
public static Func<List<string>> Callback;
Try this: Read more from here http://msdn.microsoft.com/en-us/library/bb534960%28v=vs.110%29.aspx
internal delegate int PowerOfTwo();
void Main(){
PowerOfTwo ch = new PowerOfTwo(CheckPower);
Console.WriteLine(ch());
}
int CheckPower(){
return 2*2;
}
#Torbjörn Kalin's answer is good, but only if you have only 1 delegate you want to get the return value from. If you want to retrieve the return values of more than one delegate, this is how you do it:
//Publisher class
public class ValidateAbuse
{
public delegate List<String> GetAbuseList();
public static GetAbuseList Callback;
public void Ip(string ip)
{
foreach (GetAbuseList gal in Callback.GetInvocationList())
{
List<string> result = gal.Invoke(/*any arguments to the parameters go here*/);
//Do any processing on the result here
}
}
}
//Subscriber class
class Server
{
public static void Start()
{
//Use += to add to the delegate list
ValidateAbuse.Callback += GetIpAbuseList;
ValidateAbuse.Ip(MyIp);
}
private static List<string> GetIpAbuseList()
{
//return code goes here
return new List<String>();
}
This will invoke each delegate one after the other, and you can process the output of each delegate separately from each other.
The key here is using the += operator (not the = operator) and looping through the list that is retrieved by calling GetInvocationList() and then calling Invoke() on each delegate retrieved.
I figured this out after reading this page:
https://www.safaribooksonline.com/library/view/c-cookbook/0596003390/ch07s02.html
(altho it was partially because I already had an idea what to do, and I didn't start a free trial to read the rest)
Hope this helps!

Categories

Resources