What's the Purpose of a Leading "::" in a C++ Method Call

Is it OK not to handle returned value of a C# method? What is good practice in this example?

The returned value (or reference, if it's a reference type) is pushed onto the stack and then popped off again.

No biggy.

If the return value isn't relevant, you can safely do this.

But be sure that it isn't relevant, just in case.

Here's some code:

    static string GetSomething()
{
return "Hello";
}

static void Method1()
{
string result = GetSomething();
}

static void Method2()
{
GetSomething();
}

If we look at the IL:

Method1:

.locals init ([0] string result)
IL_0000: nop
IL_0001: call string ConsoleApplication3.Program::GetSomething()
IL_0006: stloc.0
IL_0007: ret

Method2:

IL_0000:  nop
IL_0001: call string ConsoleApplication3.Program::GetSomething()
IL_0006: pop
IL_0007: ret

Exactly the same number of instructions. In Method1, the value is stored in the local string result (stloc.0), which is deleted when it goes out of scope. In Method2, the pop operation simply removes it from the stack.

In your case of returning something 'really big', that data has already been created and the method returns a reference to it; not the data itself. In Method1(), the reference is assigned to the local variable and the garbage collector will tidy it up after the variable has gone out of scope (the end of the method in this case). In Method2(), the garbage collector can get to work, any time after the reference has been popped from the stack.

By ignoring the return value, if it really isn't needed, the garbage collector can potentially get to work sooner and release any memory that's been assigned. But there's very little in it (certainly in this case), but with a long running method, hanging onto that data could be an issue.

But far-and-away the most important thing is to be sure that the return value that you're ignoring isn't something that you should be acting on.

When & why to use delegates?

I agree with everything that is said already, just trying to put some other words on it.

A delegate can be seen as a placeholder for a/some method(s).

By defining a delegate, you are saying to the user of your class, "Please feel free to assign any method that matches this signature to the delegate and it will be called each time my delegate is called".

Typical use is of course events. All the OnEventX delegate to the methods the user defines.

Delegates are useful to offer to the user of your objects some ability to customize their behavior.
Most of the time, you can use other ways to achieve the same purpose and I do not believe you can ever be forced to create delegates. It is just the easiest way in some situations to get the thing done.

C# Passing Function as Argument

Using the Func as mentioned above works but there are also delegates that do the same task and also define intent within the naming:

public delegate double MyFunction(double x);

public double Diff(double x, MyFunction f)
{
double h = 0.0000001;

return (f(x + h) - f(x)) / h;
}

public double MyFunctionMethod(double x)
{
// Can add more complicated logic here
return x + 10;
}

public void Client()
{
double result = Diff(1.234, x => x * 456.1234);
double secondResult = Diff(2.345, MyFunctionMethod);
}

Calling a function from a string in C#

Yes. You can use reflection. Something like this:

Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);

With the above code, the method which is invoked must have access modifier public. If calling a non-public method, one needs to use the BindingFlags parameter, e.g. BindingFlags.NonPublic | BindingFlags.Instance:

Type thisType = this.GetType();
MethodInfo theMethod = thisType
.GetMethod(TheCommandString, BindingFlags.NonPublic | BindingFlags.Instance);
theMethod.Invoke(this, userParameters);

How many parameters in C# method are acceptable?

There is no general consensus and it depends on who you ask.

In general - the moment readability suffers, there are too many...

Bob Martin says the ideal number of parameters is 0 and that 3 is stretching it.

32 parameters is a massive code smell. It means the class has way too many responsibilities and needs to be refactored. Even applying a parameter object refactoring sounds to me like it would hide a bad design rather than solve the issue.

From Clean Code Tip of the Week #10:

Functions should have a small number of arguments. No argument is best, followed by one, two, and three. More than three is very questionable and should be avoided with prejudice.

How can I find the method that called the current method?

Try this:

using System.Diagnostics;
// Get call stack
StackTrace stackTrace = new StackTrace();
// Get calling method name
Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);

one-liner:

(new System.Diagnostics.StackTrace()).GetFrame(1).GetMethod().Name

It is from Get Calling Method using Reflection [C#].

Interfaces — What's the point?

The point is that the interface represents a contract. A set of public methods any implementing class has to have. Technically, the interface only governs syntax, i.e. what methods are there, what arguments they get and what they return. Usually they encapsulate semantics as well, although that only by documentation.

You can then have different implementations of an interface and swap them out at will. In your example, since every pizza instance is an IPizza you can use IPizza wherever you handle an instance of an unknown pizza type. Any instance whose type inherits from IPizza is guaranteed to be orderable, as it has an Order() method.

Python is not statically-typed, therefore types are kept and looked up at runtime. So you can try calling an Order() method on any object. The runtime is happy as long as the object has such a method and probably just shrugs and says »Meh.« if it doesn't. Not so in C#. The compiler is responsible for making the correct calls and if it just has some random object the compiler doesn't know yet whether the instance during runtime will have that method. From the compiler's point of view it's invalid since it cannot verify it. (You can do such things with reflection or the dynamic keyword, but that's going a bit far right now, I guess.)

Also note that an interface in the usual sense does not necessarily have to be a C# interface, it could be an abstract class as well or even a normal class (which can come in handy if all subclasses need to share some common code – in most cases, however, interface suffices).

How do function pointers in C work?

Function pointers in C

Let's start with a basic function which we will be pointing to:

int addInt(int n, int m) {
return n+m;
}

First thing, let's define a pointer to a function which receives 2 ints and returns an int:

int (*functionPtr)(int,int);

Now we can safely point to our function:

functionPtr = &addInt;

Now that we have a pointer to the function, let's use it:

int sum = (*functionPtr)(2, 3); // sum == 5

Passing the pointer to another function is basically the same:

int add2to3(int (*functionPtr)(int, int)) {
return (*functionPtr)(2, 3);
}

We can use function pointers in return values as well (try to keep up, it gets messy):

// this is a function called functionFactory which receives parameter n
// and returns a pointer to another function which receives two ints
// and it returns another int
int (*functionFactory(int n))(int, int) {
printf("Got parameter %d", n);
int (*functionPtr)(int,int) = &addInt;
return functionPtr;
}

But it's much nicer to use a typedef:

typedef int (*myFuncDef)(int, int);
// note that the typedef name is indeed myFuncDef

myFuncDef functionFactory(int n) {
printf("Got parameter %d", n);
myFuncDef functionPtr = &addInt;
return functionPtr;
}


Related Topics



Leave a reply



Submit