Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the object type contain a protected virtual Finalize method?

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?

like image 284
Veverke Avatar asked Jul 27 '26 11:07

Veverke


1 Answers

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.

like image 126
Hamid Pourjam Avatar answered Jul 30 '26 03:07

Hamid Pourjam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!