C# Odds, Part I: “Protected” Keyword

What is wrong with this code?

public class A {
  protected int campoProtegido;
}

public class C: A {
  public void doStuff(A a) {
    a.campoProtegido = 3;
  }
}

Actually, it won’t compile. It seems that the protected keyword only works at the instance context. So, although class C is a subtype of A, because it is a different instance than the instance of A we are trying to access, it fails at compile time in line 7. So much for encapsulation…

Any ideas besides turning the field campoProtegido public?

Tags: , ,

8 Responses to “C# Odds, Part I: “Protected” Keyword”

  1. Zeca says:

    1)
    public class A {
    private int campoProtegido;
    public void setCampoProtegido(int valor) {
    campoProtegido = valor;
    }
    }

    public class C: A {
    public void doStuff(A a) {
    a.setCampoProtegido(3);
    }
    }

  2. Zeca says:

    Aparentemente, só podes aceder a campos protected se for membro da classe.
    Embora o teu “a.campoProtegido = 3″ não funcione, se criares uma instancia da classe C já consegues fazer “c.campoProtegido = 3″.

  3. Pedro Santos says:

    Maybe add a property/method for setting up campoProtegido ?
    My guess is that you can accomplish what you want in a different way, but for that I would need the overall context.

    That example soooo reminds me of C++. :P

  4. Bytter says:

    @Zeca: But that is missing the point, right? I only want campoProtegido to be accessed through subclasses of A, not expose them to public.

    @Pedro: Having a method, or a getter/setter, would expose them to everyone, not only to the subclasses (or else I would need to define it as protected, but then I would fall in the same category as the field), which is defies the purpose of hiding access to data to protect it from hostile code.

    C++ has the concept of “friend”. You can say that class X is friend of Y, so Y can access the private members of X. This is not possible in .NET. All you can say is that a member is “internal”, in the sense that methods (or classes) marked as “internal” can only be accessed by code in the same assembly.

  5. Nuno says:

    Na FEUP não dão OOP ou passaste as aulas a dormir?

  6. fasteez says:

    seems logical to me even if i failed to prove it verbally o_o

  7. I have no clue about MS#, but in real languages if you are passing an instance of A inside doStuff, it’s irrelevant if C inherits from A ot not.

    The best you can do is alter C’s own campoProtegido, inherithed from class A:

    public class C: A {
    public void doStuff() {
    campoProtegido = 3;
    }
    }

Leave a Reply