Archive

Posts Tagged ‘c++’

emulating nameof ?

October 4th, 2014 antonio elena No comments

As you might now C# 6.0 will include the new nameof keyword to allow code like this

void MyMethod(string parameter1)
{
  if(parameter1 == null)
  	throw new ArgumentNullException(nameof(parameter1));

	// ....
}

instead of having to pass the name as a string as before

void MyMethod(string parameter1)
{
  if(parameter1 == null)
  	throw new ArgumentNullException("parameter1");

	// ....
}

So far, in some of my code I was using a variation of this idea not available as such in previous versions of the language. Renaming the code to actually use a user defined function with the same “nameof” name we could have something like this (I am showing with just a quick and dirty console attribute):

static void Main ( string [] args )
        {
            MyMethod ( null );
        }
        static void MyMethod ( string parameter1 )
        {
            throw new ArgumentNullException ( nameof ( parameter1 ) );
        }
        static string nameof ( object p )
        {
            // get previous stack frame
            StackFrame frame = new StackFrame ( 1 );
            // inspect the caller
            MethodBase method = frame.GetMethod ();
            // and get the name of the first parameter defined in the caller's signature
            return frame.GetMethod ().GetParameters ().First ().Name;
        }
    }

Naturally, this is not so straigthforward when there are more arguments and the one we want might not be the first one, but the nth argument in the signature. The first solution that comes to mind then is passing the position when throwing the ArgumentNullException:

static void MyMethod ( string parameter0, string parameter1 )
        {
            try
            {
                throw new ArgumentNullException ( nameof ( parameter1, 1 ) );
            }
            catch ( Exception ex )
            {
                Console.WriteLine (ex.Message);
            }
            Console.ReadLine ();
        }
        static string nameof ( object p, int pos = 0 )
        {
            // get previous stack frame
            StackFrame frame = new StackFrame ( 1 );
            // inspect the caller
            MethodBase method = frame.GetMethod ();
            // and get the name of the first parameter defined in the caller's signature
            return frame.GetMethod ().GetParameters ().ElementAt ( pos ).Name;
        }

However, even when declaring the position as an optional parameter so as to have a cleaner case when the parameter we are interested in is the first one, this is not perfect as it introduces an additional element that the caller has to care about.

But at least, you avoid hardcoding parameter names in situation like this, which is a good thing when you want to rename objects. It’s easier this way.

The new nameof expression, however, is not limited to scenarios like this. You can actually get a hold of any programming construct via nameof.

Take this example from msdn magazine

[TestClass]
  public class NameofTests
  {
    [TestMethod]
    public void Nameof_ExtractsName()
    {
      Assert.AreEqual<string>("NameofTests", nameof(NameofTests));
      Assert.AreEqual<string>("TestMethodAttribute",
        nameof(TestMethodAttribute));
      Assert.AreEqual<string>("TestMethodAttribute",
        nameof(
         Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute));
      Assert.AreEqual<string>("Nameof_ExtractsName",
        string.Format("{0}", nameof(Nameof_ExtractsName)));
      Assert.AreEqual<string>("Nameof_ExtractsName",
        string.Format("{0}", nameof(
        CSharp6.Tests.NameofTests.Nameof_ExtractsName)));
    }
  }

With reflection we can do similar things, but it all feels quite clumnsy, as we cannot really do something like this:

 static void Main ( string [] args )
     {
         // apparently you cannot pass 'Main' like this...
         Console.WriteLine ( nameof ( Main ) );
     }
     // this is fantasy, there is no such 'MethodGroup' class
     static string nameof ( MethodGroup m )
     {
         // get the name of such MethodGroup instance...
         return null;
     }

Sadly there is no such thing as a MethodGroup.A MethodGroup is an internal type used by the compiler in order to keep track of the expression so far. It’s not an LValue and you can’t put it in a variable; it doesn’t inherit from anything and it doesn’t have a .NET Type.

Apart from the fact that class MethodGroup does not exist, there is a workaround, that feels also not so good, that involves creating an Action and to enable casting to a delegate like this:

static void Main ( string [] args )
{
	Console.WriteLine ( nameof ( new Action ( Method ) ) );
}
static void MyMethod ()
{
}
static string nameof ( Delegate d )
{
    return d.Method.Name;
}

Or we can leverage expression trees:

static void Main ( string [] args )
        {
            Console.WriteLine ( nameof ( () => Main(args) ) );
        }
        static void MyMethod ()
        {
        }
        static string nameof ( Expression<Action> expr )
        {
            // get previous stack frame
            StackFrame frame = new StackFrame ( 1 );
            // inspect the caller
            MethodBase method = frame.GetMethod ();
            return method.Name;
        }

Or without using StackFrame at all:

 static void Main ( string [] args )
        {
            Console.WriteLine ( nameof ( () => Main(args) ) );
        }
        static void MyMethod ()
        {
        }
        static string nameof ( Expression<Action> expr )
        {
            var call = ( MethodCallExpression ) expr.Body;
            return call.Method.Name;
        }

In that way we can access our Main method.

There are other options…. for example leveraging AOP frameworks such as PostSharp or Fody to introduce IL-weaving code that simulates the same effect.

A simpler option is to create a simple Enum to tell our makeshift nameof to inspect either our class name or other higher level constructs such as those from the real nameof example. For example:

public enum InspectionLevel
    {
        CLASS,
        ASSEMBLY,
        ATTRIBUTES
    }

And the rest would be standard reflection code. No big deal. The new nameof of course makes things much easier in this sense.

spacer
Categories: .net Tags: .net, c++, reflection

just for fun

September 17th, 2013 antonio elena No comments

factorial in C# using the yields keyword. Gets quick results even for large numbers by using the BigInteger type in C# 4.0 (you need to add a reference to the System.Numerics dll). Have fun watching the .net performance counters on this (GC Generations and collections, etc).


private static IEnumerable<Tuple<BigInteger, string>> Factorial(int number)
{
     BigInteger accumulator = number;
     var i = 1;
     while (number > 1)
     {
            accumulator *= --number;
            yield return new Tuple(accumulator,
                    String.Format("{0} * {1} = {2}", number + 1, number, accumulator));
      }
}

Use as in:


foreach (var j in Factorial(number))
                    Console.WriteLine("{0} - {1}", j.Item1, j.Item2);
spacer
Categories: .net, justforfun Tags: .net, c++

Review of Cocos2D-X, beginner’s guide

May 12th, 2013 antonio elena No comments


spacer

It’s been a busy week with book reviews. Apart from the meteor book (see next post), I also was reviewing this book, also by invitation of the publisher.

As with other beginner’s books by this publisher, the book starts by indicating the installation process, and the proverbial “hello, world” project. The example is very trivial, but serves the important explanation of project structure, what’s what in the project. Testing gets paid attention, which is nice, and then some recommendations on additional tools for sprites, textures etc. Maybe the absolute beginner can feel a little bit daunted by the amount of info to digest in the first chapter, regarding the many classes and infrastructure that you need to make a simple hello world. Luckily as the book progresses the concepts get clarified and expanded on, and that is what chapter 2 does, because obviously the hints in the chapter 1 are not enough.

I personally prefer books that explain things first rather than other books that expect you to infer things from examples. I like that Chapter 2 explains the pieces that make Cocos tick, the Containers, Nodes, Scenes, Layers, the Director, Caches etc. The author then proceeds to guiding the unexperienced developer to a basic understanding of C++ Classes, header files and all, explaining almost every line, and finishes off by bridging the differences between C++ developers and Cocos2D developers so they are familiar with the common ground offered by the framework.

Without further ado, Chapter 3 sees us create the first game, where we finally start to see some action by adding resources, preloading sounds, targeting retina displays, extending CCSprite, and even adding multitouch. It’s nice because a functional game is created step by step. One also realizes that game dev is relatively complex even when it’s a simple game. The book again follows the way of showing the code and then proceeding to explain it line by line. Chapter 4, builds on the previous chapter to build now a different, more complex game. We’re not just stuck to simple examples.

Chapter 5 continues wit this dynamic, building a different game, this time about rockets, this time introducing some particle physics, as the next level of complexity in your games.

Chapter 6. Different game. The twist comes with the introduction of testing and rapid prototyping using placeholders with the Cocos2D platform. The author now reveals this is how he created every example in the book. Abundant screenshots and lots of code accompany here. I think the chapter is well placed. You’ve followed how to code a couple of simple games, then you’re shown some “secrets” and techniques for testing your ideas before investing lots. After the prototyping, chapter 7 actually builds the game with the real graphics, so you get the whole picture from concept testing to actual implementation.

Chapter 8 introduces Box2D, for adding realistic physics, that would be way too much effort to do on your own. Project creation is a breeze, but you got to take account of the differences between coding a game with Cocos and with Box (different classes, basically). It can look simplistic, in the sense that even when using a game library, a lot of tweaking for the right values of trajectories, where to place things, etc must be done.

Chapter 9 rounds off our game coding by introducing ancillary aspects, like reading/writing data, scenes, transitions, etc, which not being vital, are things every game needs. For me the game in this “level” ;-) is the funniest, but I am a platform buff. Notifications, via the observer pattern, are introduced too. Using the accelerometer in the device.

Chapter 10 closes the book by paying attention to what used to be a hell for me ten years ago when doing games for the j2me platform: portability. You get warned and then led to creating different projects for different devices / platforms and some additional tools. Appendix A then gives you some vector course 101 if you were a bit weak in that aspect.

Needless to say, a book like this is code-intensive, otherwise it would not be much worth. You could say that it reads as a series of tutorials of increasing complexity, the main chapters being self contained in this sense, which is good if you want to complete chapters one by one in easy sittings.

The games cannot be complex production pieces, that would exceed any book’s scope, but I think they are enough to motivate you to start coding some game of your own. In that sense, the book gives you a more than adequate basis. For sure, if you not only read the book but take the trouble to type and make some changes of your own to the book, you will no doubt spend quite some hours engrossed with learning all this stuff. Be sure to check the code download, full of comments not present in the book for obvious reasons.

All in all, I’d say the book in this case is more than a beginner’s guide. Nobody becomes a master of anything with just one book, but this one sets you off handsomely.

spacer
Categories: books, coding Tags: books, c++, Cocos2D, macosx
gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.