Learning Through Reading Code

I’ve started reading a lot of code lately from all kinds of different sources.  It’s pretty easy to find new tricks and techniques when reading someone else’s code.  Open source projects and blogs are great places to find code to look over.  Microsoft even has  a site dedicated entirely to sample code.  I like these projects because they’re small and categorized so you can quickly filter to what you’re interested in.

There’s also a free app that you can download to easily browse through over 3500 projects.

How to Create a Hidden Property or Method That’s Still Public

Have you ever needed to hide a property or method on a class, but still needed to access it outside of the class?  Obviously declaring the property as “internal” will only allow the property to be accessible from within the same assembly, but what if you needed to access it outside of the assembly, but also didn’t want to make it public for others to see.  An example of this might be a business entity that you allow customers to retrieve and save data using a WCF service client.  The entity exposes properties that represent a business object that you persist to a database.  The entity is also used in other business processes which require information that you don’t want to expose as part of the entity.

The following method describes a technique to add a property or method to a class that isn’t directly accessible on the entity, but is available explicitly through an interface.

1. First let’s create an entity with a public property.

    public class MyEntity
    {
        /// <summary>
        /// My Public Property
        /// </summary>
        public string MyPublicProperty { get; set; }
    }

2.  Now, let’s create an interface with a property that we want to use on the entity.

public interface IMyHiddenPropertiesInterface
{
string MyInterfaceProperty { get; set; }
}

3.  Now, have the entity implement the interface, but explicitly implement the interface property. I’ve also overriden the “ToString” method so we can print out the property values later.

public class MyEntity : IMyHiddenPropertiesInterface
{
/// <summary>
/// My Public Property
/// </summary>
public string MyPublicProperty { get; set; }

/// <summary>
/// My Explicit Implementation of my interface property
/// </summary>
string IMyHiddenPropertiesInterface.MyInterfaceProperty { get; set; }

public override string ToString()
{
return MyPublicProperty + " " + ((IMyHiddenPropertiesInterface)this).MyInterfaceProperty;
}
}

4. Finally, here’s a console app that creates an entity and sets both of the properties.

class Program
{
static void Main(string[] args)
{
// Create a new entity and set the public property
MyEntity entity = new MyEntity() { MyPublicProperty = "Hello" };

// Set the hidden property
IMyHiddenPropertiesInterface entityInterface = (IMyHiddenPropertiesInterface)entity;
entityInterface.MyInterfaceProperty = "World!";

Console.WriteLine(entity.ToString());
Console.ReadLine();
}
}

Notice when you look at the meta data associated with entity that you don’t see the MyInterfaceProperty.  That’s because it’s only accessible through the interface.

Here’s what you see when you look at the interface data from intellisense.

MyInterfaceProperty is hidden when acting on the MyEntity variable, but it’s available explicitly through the interface.  This allows you to hide data on your entity that you don’t want customers to easily access and still make it publicly available outside of the assembly.  If your entity code is publicly available to your consumers and their code savy, then they can get to your property, but it’s not as easy as making it public.

Here’s the program output when executed:

Explicit interface implementation is ideal for classes that implement multiple interfaces with the same properties or method names, but since explicit implementation doesn’t make the properties available directly on the class, it’s also a tricky way of hiding something that you don’t want to make public.  Another option is to make your property internal and create a public utility class within the same assembly that can access the property.   This works just as well since it makes it much less obvious to consumers outside of your assembly that there’s hidden data on the entity.

Related Articles:

MSDN Explicit Interface Implementation

Free Microsoft Book: Patterns for Parallel Programming: Understanding and Applying Parallel Patterns with the .NET Framework 4

 

Thought I’d share in case you don’t already have this.  Has lots of examples and is pretty thorough.

Patterns for Parallel Programming: Understanding and Applying Parallel Patterns with the .NET Framework 4

http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=19222

 

Here’s the Overview:

This document provides a detailed and in-depth tour of support in the Microsoft® .NET Framework 4 for parallel programming. This includes an examination of common parallel patterns and how they’re implemented without and with this new support in the .NET Framework, as well as covering best practices for developing parallel components utilizing parallel patterns.

 

Tip: How to Concatenate a Required Argument to a Params Array

Here’s a simple trick that allows you to quickly add a required method argument to a params array of the same type.

The example method below simply returns the minimum of all integers passed into the method where at least one integer is required.

        private static int Min(int value1, params int[] valuesArray)
        {
            int? minFromArray = null;

            if(valuesArray != null)
                minFromArray = valuesArray.Min();

            return (minFromArray.HasValue && minFromArray.Value < value1 ? minFromArray.Value : value1;
        }

A trick to turn the method into one line of code is to use the Concat method.

        private static int Min(int value1, params int[] valuesArray)
        {
            return valuesArray.Concat(new[] { value1 }).Min();
        }