Search code examples
c#.net.net-assemblyassembliessystem.reflection

Relation between IsAssembly / IsFamily and IsFamilyOrAssembly


IsAssembly, IsPublic, IsFamily, IsFamilyOrAssembly, IsFamilyAndAssembly I have read about this but I am not able to understand what each one does. The strange thing here is IsFamily and IsAssembly returns False in the code but IsFamilyOrAssembly returns True.

Can someone give an explanation for each of this property as I find it difficult to understand from the documentation.I came across all this when I started reading about Reflection in c#.

public class Example
{
    public void m_public() {}
    internal void m_internal() {}
    protected void m_protected() {}
    protected internal void m_protected_public() {}

    public static void Main()
    {
        Console.WriteLine("\n{0,-30}{1,-18}{2}", "", "IsAssembly", "IsFamilyOrAssembly"); 
        Console.WriteLine("{0,-21}{1,-18}{2,-18}{3}\n", 
            "", "IsPublic", "IsFamily", "IsFamilyAndAssembly");

        foreach (MethodBase m in typeof(Example).GetMethods(
            BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
        {
            if (m.Name.Substring(0, 1) == "m")
            {
                Console.WriteLine("{0,-21}{1,-9}{2,-9}{3,-9}{4,-9}{5,-9}", 
                    m.Name,
                    m.IsPublic,
                    m.IsAssembly,
                    m.IsFamily,
                    m.IsFamilyOrAssembly,
                    m.IsFamilyAndAssembly
                );
            }
        }
    }
}

This code example produces output similar to the following:

                              IsAssembly        IsFamilyOrAssembly
                     IsPublic          IsFamily          IsFamilyAndAssembly

m_public             True     False    False    False    False
m_internal           False    True     False    False    False
m_protected          False    False    True     False    False
m_protected_public   False    False    False    True     False

Solution

  • Member of a Class have access modifiers associated with them (public, internal,...). These define the level of object-oriented encapsulation implemented by the member. You can find more details at here.

    Using Reflection, you might want to have a look at:

                        /*Modifiers*/
    
    IsPublic            public
    
    IsFamilyOrAssembly  protected internal
    
    IsFamily            protected
    
    IsFamilyAndAssembly private protected (since C# 7.2)
    
    IsAssembly          internal
    

    When you want to determine if a member is visible in inherited types, you need to check using the expression (m.IsFamilyOrAssembly || m.IsFamily || m.IsFamilyAndAssembly || m.IsAssembly). And exactly only one of these properties is true and all of the others are false.