-5

I have a 2 classes one is base class and second is derived class. Want to restrict object slicing, how can I do it using C#.net ?

Neeraj Kumar Gupta
  • 2,157
  • 7
  • 30
  • 58
  • 2
    Can you give us some more info? e.g. with some code examples what you want to achieve. – Erwin Oct 03 '12 at 13:55
  • 3
    You don't need to worry about slicing in C#. See this very similar [question](http://stackoverflow.com/q/536267/944681) – Michal Klouda Oct 03 '12 at 14:05
  • Do you mean the `sealed` keyword to prevent derived classes to overwritte some methods or an entire class? (see [sealed on MSDN](http://msdn.microsoft.com/en-us/library/88c54tsw%28v=vs.100%29.aspx)) – Matten Oct 03 '12 at 13:58
  • I want to know, can we prevent object slicing in .net ? – Neeraj Kumar Gupta Oct 03 '12 at 14:02

1 Answers1

0

UPDATE:

My initial thoughts as described below were found as not true: See: C++ slicing in Java / C#


Original Answer:

If I understood correctly this is a theoretical question. REDUCING slicing can be done by not defining new members in the derived class.

slicing occurs when assigning an instance of a derived class to a base class reference type. In this case the system does not know where to allocate a new data-type because it is defined in the derived class only and not in the base class.

But there is no way to RESTRICT that, this is what suppose to happen and it is defined as

A natural and unavoidable consequence of assignment by value from subclass objects

Object slicing - Wikipedia

however you can declare a class as sealed to prevent inheritance that will restrict object slicing because it will prevent the cause (Inheritance) so you will not have a derived class to assign to a base reference by value.

Community
  • 1
  • 1
Mortalus
  • 10,574
  • 11
  • 67
  • 117
  • the link you provided deals with C++, not C#. The question asks about slicing in C# – default Oct 03 '12 at 14:10
  • True, but the concept of object slicing is theoretical and language agnostic. every language that can provide a value-type structured memory stream e.g. structs or classes will deal with the issue called object-slicing. – Mortalus Oct 03 '12 at 14:13
  • not according to [this answer](http://stackoverflow.com/a/536290/238902) – default Oct 03 '12 at 14:15
  • every day you learn some thing new... :) – Mortalus Oct 03 '12 at 14:17