3

C# 6.0 in a Nutshell by Joseph Albahari and Ben Albahari (O’Reilly).

Copyright 2016 Joseph Albahari and Ben Albahari, 978-1-491-92706-9.

states, at pages 100-101, that the object class members are:

public class Object
{
    public Object();
    public extern Type GetType();
    public virtual bool Equals (object obj);
    public static bool Equals (object objA, object objB);
    public static bool ReferenceEquals (object objA, object objB);
    public virtual int GetHashCode();
    public virtual string ToString();
    protected virtual void Finalize(); //<-- this one
    protected extern object MemberwiseClone();
}

which prompted me to go check if VS's intellisense gives me a Finalize() method for any reference instance, since I do not remember ever seeing one.

I do not succeed in getting such an object with a Finalize member inherited (I am trying to access it inside the function, aware of the fact it is protected).

I checked .NET's open source code and the object.cs file does not contain a Finalize method.

What am I missing ? Is this a mistake from the author?

Veverke
  • 9,208
  • 4
  • 51
  • 95

1 Answers1

4

From MSDN:

The C# compiler does not allow you to override the Finalize method. Instead, you provide a finalizer by implementing a destructor for your class. A C# destructor automatically calls the destructor of its base class.

You must use ~ClassName() to implement a destructor.

Object.cs is written in C# so it has ~Object() instead of Finalize().

I suggest that you read this article and this answer

From Eric Lippert:

This feature is confusing, error-prone, and widely misunderstood. It has syntax very familiar to users of C++, but surprisingly different semantics. And in most cases, use of the feature is dangerous, unnecessary, or symptomatic of a bug.
Sometimes you need to implement features that are only for experts who are building infrastructure; those features should be clearly marked as dangerous—not invitingly similar to features from other languages.

Community
  • 1
  • 1
Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74