Click here to Skip to main content
15,898,679 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
I'm just starting out with c# so the question may appear little trivial. But I couldn't find an answer (I wished to look for)
as in c I can create a small macro to e.g. print the name and value of a constant
C++
#define print_it(x) printf("Name: %s, Value: %d", ##x, x)

and if I have a symbol like
C++
#define  CUBE_ARM_WIDTH 5

I'd do it like
C++
print_it(CUBE_ARM_WIDTH);

and I'd get the output as
Name: CUBE_ARM_WIDTH, Value: 5

But how do I do it in c#, where #define is allowed but to give it a value or a function like body is not allowed.
and also suppose I am using a constant value in two different cs files, something like
C++
#define GRID_ARRAY_WIDTH  20

I'll put it in a header file, include it in both files and use the name I #defined freely. But the same can not be done in c# with the same ease.
I know we can use enums. but in that case:
C#
class myShapes
  {
    enum GridParams
    {
      GridArrayWidth  20,
      GridArrayHeight  20
    };
  }

my the name that was already a little long, becomes even longer i.e.
C#
myShapes.GridParams.GridArrayWidth

with #define it was 16 characters long and now it is 34 characters.
I think there should be a better way of doing it, which apparently, I have not come across.
So how do I do these things in C#.
Please don't get me wrong, I admire C# a lot for a simple fact that what I could do in VC++ with some files-full of code can be done in few lines in c# which are simple and very intuitive.
I just want to know if I can use some of the things I learned while using C.

Regards,
gdshukla
Posted

You can use a static function for these things

C#
namespace MyNamespace
{
    public static class MyFunctions
    {
        public string DoSomething (string p)
        {
            return p.ToUpper();
        }
    }
}


then to use

C#
string x = MyNamespace.MyFunctions.DoSomething("hello");
 
Share this answer
 
C# does not have any macro preprocessing of this type.
There is nothing like macro #x or a ## b.
Likewise, since there is no substitution process,
#define CUBE_ARM_WIDTH 5
doesn't really make sense.

So, yes, some things are more verbose in C# than in C/C++.
Most of us have found that the benefits outweigh the extra verbosity.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900