Attributes vs Interface: best practice?

E

Eric Jacoboni

Hi,

I've some question about best programming practice in C#.

Suppose i want a serializable class with transient member and recreate
this member on deserialization.

I've found i may use these two approaches:

1) Using interfaces:

[Serializable]
class Truc : IDeserializationCallback {
private int limite;
[NonSerialized]
private int[] tab;
(...)
public virtual void OnDeserialization(Object sender) { ... }
}

2) Using attributes only:

[Serializable]
class Truc {
private int limite;
[NonSerialized]
private int[] tab;
(...)
[OnDeserialized]
public virtual void OnDeserialized(StreamingContext context)
{ ... }
}

Both do what i expect but i wonder if one approach is considered better
than the other.

Any advice?
 
I

Ignacio Machin ( .NET/ C# MVP )

Hi,

I've some question about best programming practice in C#.

Suppose i want a serializable class with transient member and recreate
this member on deserialization.

I've found i may use these two approaches:

1) Using interfaces:

[Serializable]
class Truc :   IDeserializationCallback {
  private int limite;
  [NonSerialized]
  private int[] tab;
  (...)
   public virtual void OnDeserialization(Object sender) { ... }

}

2) Using attributes only:

[Serializable]
class Truc  {
  private int limite;
  [NonSerialized]
  private int[] tab;
  (...)
  [OnDeserialized]
  public virtual void OnDeserialized(StreamingContext context)  
  { ... }

}

Both do what i expect but i wonder if one approach is considered better
than the other.

Any advice?

It's the same I believe.
Note that you do not need to use either way, the only case when you
need to use it is when you need to perform a special operation after
the object is deserialized but before it's returned to the calling
code. Honestly I have never had a need for such a case.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top