Question

I have a partial class that is split over two namespaces. The problem is that if I have an interface implemented on one of the partials, it is not recognized on the counterpart partial class. For example, I would expect the below to return true for being recognized as ILastModified (C# fiddle at http://ideone.com/heLDn0):

using System;
using MyNamespace.One;
 
public class Test
{
    public static void Main()
    {
        var item = new Product();
        Console.WriteLine(item is ILastModified); //RETURNS FALSE??!
    }
}
 
interface ILastModified
{
    DateTime LastModified { get; set; }
}
 
namespace MyNamespace.One
{
    public partial class Product
    {
        public int ID { get; set; }
    }
}
 
namespace MyNamespace.Two
{
    public partial class Product : ILastModified
    {
        public DateTime LastModified { get; set; }
    }
}
Was it helpful?

Solution

You cannot have a partial class in two different namespaces. The compiler treats those as two different classes.

OTHER TIPS

I have a partial that is split over two namespaces.

You can't. By being in different namespaces, they are different classes.

Consider that this is the reason namespaces exist - so you can have the same class name for different classes.

From the C# Language Specification (C# 4.0), §10.2, Partial types:

Each part of a partial type declaration must include a partial modifier. It must have the same name and be declared in the same namespace or type declaration as the other parts.

(emphasis mine)

So, by definition, what you are doing is not a partial type.

See Partial Class Definitions

Using the partial keyword indicates that other parts of the class, struct, or interface can be defined within the namespace.

This is due to the fact that partial types must be within the same namespace because each class has a fully quantified name which includes the namespace. A prime example of this is with Windows Forms Application the designer and the UI code are seperated using a partial class. It also prevents bad design in my opinion!

You can see this for yourself using simple reflection code (for fun mostly).

var namespaces = Assembly.GetExecutingAssembly().GetTypes()
                         .Select(t => t.Namespace)
                         .Distinct();

//Returns:
//  WindowsFormsApplication2
//  WindowsFormsApplication2.Properties

Namespaces provide logical seperation of Types. MyNamespace.One.Product and MyNamespace.Two.Product are two different types (if this were not the case, then there would be no point in having Namespaces in the first place!)

Because of using MyNamespace.One;,

In Main():

var item = new Product();

is the equivalent of:

var item = new MyNamespace.One.Product()

Change the namespace of the second Product type to MyNamespace.One

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top