Nick’s Code

Search

XNA MVP

Contact

Donate

Categories

Latest News

Twitter


follow nickgravelyn at http://twitter.com



RSS Feed

My Fishes

Posted in .NET, C# on June 15, 2008 at 12:55am.
There is one comment.

While trying to explain how to learn coding to some people, I wanted to find this fun little console application I had written a long time ago. Basically in trying to prove that you can do lots of things in console applications, I wrote up an animated fish tank that runs in a console window. Complete with multiple colored fish, all of which blowing bubbles, I think this demonstrates to beginners just how much you can do in a console application.

Hopefully this can be a resource to others that it is worth spending time making console applications. Get familiar with the language and you can do all sorts of cool things with it. Don’t rush into XNA or any other graphics API until you have the fundamentals down. And besides, how cool is it to have an animated fishtank in a console window? :)

Here’s the whole source file for anyone to play with: FishTank.cs.



Let’s Talk C# Features, Pt 4

Posted in .NET, C#, XNA on May 14, 2008 at 1:43pm.
There are 2 comments.

We’ve covered all of the purely compile-time tricks for C# 3.0. Now we’re going to talk about a new feature that will only work on PC (until the .NET CF on Xbox 360 and Zune get updated): extension methods. Extension methods are great for those times when you find yourself writing helper methods for classes and thinking “I wish this was part of the API”. For instance let’s say you have a small Sprite class for your game:

public class Sprite
{
	public Texture2D Texture { get; set; }
	public Vector2 Position { get; set; }
	public Color Color { get; set; }
}

Now we want to add a way to render it using a SpriteBatch. You previously would probably add a method to the Sprite class that looked like this:

public void Draw(SpriteBatch spriteBatch)
{
	spriteBatch.Draw(Texture, Position, Color);
}

And then to render you would create a Sprite and SpriteBatch and call that method:

Sprite sprite = new Sprite();
SpriteBatch spriteBatch = new SpriteBatch(GraphicsDevice);

sprite.Draw(spriteBatch);

Not too bad, right? Except it doesn’t quite look right. The method looks like the Sprite is drawing the SpriteBatch. Clearly not what we want. Ideally we want something like this:

spriteBatch.Draw(sprite);

Well now you can using extension methods. An extension method is simply a static method where the first parameter is qualified with the ‘this’ keyword. So we could take our Draw method above and place it into a new, static class like this:

public static class SpriteBatchExtensions
{
   public static void Draw(
        this SpriteBatch spriteBatch,
        Sprite sprite)
   {
	spriteBatch.Draw(
                sprite.Texture,
                sprite.Position,
                sprite.Color);
   }
}

So this is just a standard public static method but that ‘this’ keyword adds a whole new functionality to it. We can still call this method just like we would before extension methods:

Sprite.Draw(spriteBatch, sprite);

But because we have the ‘this’ keyword on that first parameter we can now call it like we wanted to:

spriteBatch.Draw(sprite);

What does this all mean in the grand scheme of things? APIs are no longer set in stone. You can now make these methods that attach to the types that they work for. They still act like normal static methods in that you don’t get any access to protected or private data, and you do still have to have access to the method (so it can’t be a private or protected static method or in a non-public class), but now you can have more logically written code where actions are actually performed on the objects they affect.

As another quick example, let’s look at some pretty standard code most people run when they draw a model in XNA:

foreach (ModelMesh mesh in myModel.Meshes)
{
	foreach (BasicEffect effect in mesh.Effects)
	{
		effect.EnableDefaultLighting();
		effect.World = world;
		effect.View = view;
		effect.Projection = projection;
	}
	mesh.Draw();
}

We could easily stick that into an extension method like this:

public static void Draw(
                this Model model,
                Matrix world,
                Matrix view,
                Matrix projection)
{
	foreach (ModelMesh mesh in model.Meshes)
	{
		foreach (BasicEffect effect in mesh.Effects)
		{
			effect.EnableDefaultLighting();
			effect.World = world;
			effect.View = view;
			effect.Projection = projection;
		}

		mesh.Draw();
	}
}

And now when we want to render out a model we can just call it as if the Model had this Draw method all along:

myModel.Draw(world, view, projection);

It’s a very slick feature and very powerful. Unfortunately this doesn’t work on Zune or Xbox 360 for now, but hopefully it will get support in the not-to-distant future.



Let’s Talk C# Features, Pt 3

Posted in .NET, C#, XNA on May 13, 2008 at 12:34am.
There are 3 comments.

This will be my last post tonight and coincidentally the last feature of C# 3.0 that will work for all platforms. This compiler trick is the new “implicitly typed local variable”. What does that mean? It means that, for local variables, you no longer have to type the variable type if you also instantiate or initialize it on that same line. The compiler will infer the type from the rest of the line and fill in the type for you. This new feature is done through the ‘var’ keyword. So for instance where you used to write something like this:

string a = "Hello World";

You can now write it like this:

var a = "Hello World";

Before I continue let me clear two things up that some of you might not get right now. First of all this is only for local variables. This means variables that exist only in the scope of a single method. Class level variables, properties, parameters, and method return values cannot be implicitly typed. Secondly this is not weak typing of variables. This is simply a compiler trick so you type less. With the above line the compiler and Intellisense both know of which type is ‘a’. So when you type a followed by a period, you’ll see the same Intellisense help you’ve always seen for a string type. No weak typing; just less typing. :)

So now you are wondering, “Gee, Nick, this is great and all, but that’s not saving me that much work.” Well we haven’t gotten to the fun stuff yet. Let’s say you have a class called Client and a class called FinanceReport. Let’s now say you want to make a local dictionary using Client for the key and a list of FinanceReports for the value. This is normally what you would see for that declaration:

Dictionary<Client, List<FinanceReports>> clientFinanceReports =
       new Dictionary<Client, List<FinanceReports>>();

That looks like an awful long line for something as simple as that. With implicit typing, though, we can reduce the line by a large amount:

var clientFinanceReports =
       new Dictionary<Client, List<FinanceReports>>();

Way shorter now. And you can also use var for things like for and foreach loops to make things easier. Let’s say we have that above dictionary and we want to iterate over all the key-value pairs. Previously this is what our loop would look like:

foreach (KeyValuePair<Client, List<FinanceReports>> keyValuePair
                in clientFinanceReports)
{
    //do something useful
}

And now with implicit typing:

foreach (var keyValuePair in clientFinanceReports)
{
    //do something useful
}

How nice is that? You no longer have to write all that generics stuff to loop over the collection saving you lots of typing time.

So remember, everything I’ve shown so far (implicit typing, collection initializers, object initializers, and auto-implemented properties) are all compiler tricks meaning that these will work already on the Zune and Xbox 360 in addition to Windows. The rest of the features I’ll be showing in the next couple days will not work on Zune or Xbox 360 because they do require some runtime enhancements to function properly.



Let’s Talk C# Features, Pt 2

Posted in .NET, C#, XNA on May 13, 2008 at 12:14am.
There are no comments.

I’m on a roll with using the new features in my own code so let’s keep going with more of the compiler tricks you can already use on all the platforms. I want to hit on two closely related topics in this post: object initializers and collection initializers.

Previously in C# if you wanted to create a list with some values you had instantiate the list and run the Add method a bunch with values like this:

List values = new List();
values.Add(1);
values.Add(2);
values.Add(3);
values.Add(4);
values.Add(5);

Well this sucks. You wind up typing a lot of the same code over and over again. In come collection initializers to the rescue. Starting with C# 3.0 you can now instantiate and populate the list in a single statement like this:

List values = new List() { 1, 2, 3, 4, 5 };

How’s that for efficiency? All on one line, no less. And like I said above this is a compiler trick that expands out to the same as above so it works on Zune and Xbox 360. Not only that but it works on most, if not all, of the built in collection types in .NET including List, Queue, Dictionary, etc.

The second topic is the object initializers. Let’s take a look at a simple structure that holds three values:

public struct SomeStruct
{
	public int Value1 { get; set; }
	public float Value2 { get; set; }
	public bool Value3 { get; set; }
}

Let’s say you want to be able to instantiate an object of this type using any combination of setting those values. To do this you used to have to write out every combination as a constructor. For this three value struct you get this:

public struct SomeStruct
{
	public int Value1 { get; set; }
	public float Value2 { get; set; }
	public bool Value3 { get; set; }

	public SomeStruct(int value1) { }
	public SomeStruct(int value1, float value2) { }
	public SomeStruct(int value1, bool value3) { }
	public SomeStruct(int value1, float value2, bool value3) { }
	public SomeStruct(float value2) { }
	public SomeStruct(float value2, bool value3) { }
	public SomeStruct(bool value3) { }
}

That’s a pain to do. Then let’s imagine it for a structure with ten or twenty values. Not very fun. This problem is easily solved with object initializers. Object initializers look a lot like collection initializers, but they let you set the values of any public properties on a type while instantiating. So now we can easily instantiate the above structure in any way we want without having to write these constructors:

SomeStruct a = new SomeStruct();
SomeStruct b = new SomeStruct() { Value2 = 1.5f };
SomeStruct c = new SomeStruct()
{
      Value1 = 10,
      Value2 = 1.5f,
      Value3 = false
};

Now no matter how many values you have in the structure you can always feel like you have a constructor that sets all of them.

Then we can now take these concepts and combine them so that we can create a list of complex types all in a single statement:

List values = new List()
{
	new SomeStruct() { Value1 = 1 },
	new SomeStruct() { Value1 = 2, Value2 = 1.5f },
	new SomeStruct() { Value1 = 3, Value3 = false },
	new SomeStruct()
        {
             Value1 = 4,
             Value2 = 1.5f,
             Value3 = true
         },
};

Pretty awesome stuff, huh? And once more, these are all compiler tricks in C# 3.0 meaning you can get started using them on your Windows, Xbox 360, and Zune games.



Let’s Talk C# Features, Pt 1.5

Posted in .NET, C#, XNA on May 13, 2008 at 12:00am.
There are 4 comments.

So the one part of the auto-implemented features I forgot to touch on was how you can make this better than just public fields. Let’s look at two versions of a class, one using auto-implemented properties and one with public fields. First our auto-implemented property version.

public class MyClass
{
	public float Value { get; set; }
	public string AnotherValue { get; set; }
	public bool SomethingElse { get; set; }
}

And now our public field version:

public class MyClass
{
	public float Value;
	public string AnotherValue;
	public bool SomethingElse;
}

Well now it looks like we’re getting the shaft with our properties, right? Not quite. Let’s say you suddenly decide that the Value property should be set through a constructor. This means it has to be get-only to the outside world. This is easy with auto-implemented properties since you can tack on an access modifier to the set property inside of there. So to make Value read-only, our class now looks like this:

public class MyClass
{
	public float Value { get; private set; }
	public string AnotherValue { get; set; }
	public bool SomethingElse { get; set; }

        public MyClass(float value)
        {
               Value = value;
        }
}

And for our public field version? Well we could decide we were wrong and switch to auto-implemented properties, or we can do this the old fashion way. We’d mark our field as ‘private’ and add a get-only property to the class (as well the constructor like above).

public class MyClass
{
	private float value;
	public string AnotherValue;
	public bool SomethingElse;

        public float Value
        {
                get { return value; }
        }

        public MyClass(float value)
        {
               this.value = value;
        }
}

So we see that auto-implemented properties are not only almost as short as public fields, but you can quickly turn them into read-only properties with much less code than our field version.



« Previous Entries