'c' is a variable but is used like a type

BenTam-3003 686 Reputation points
2022-07-30T05:19:47.257+00:00

Hi All,

I am creating a BaseForm for subclassing forms. During my writing, I encounter an error "'c' is a variable but is used like a type". It blocks me from further coding.

226329-variable.gif

Xpanel in BaseControlLibrary

using System;  
using System.Windows.Forms;  
  
namespace BaseControlLibrary  
{  
    public partial class Panel : UserControl  
    {  
        public Panel()  
        {  
            InitializeComponent();  
            int DefaultTop = Top;  
            int DefaultLeft = Left;  
            int DefaultHeight = Height;  
            int DefaultWidth = Width;  
        }  
    }  
}  

BaseForm

using System;  
using System.Windows.Forms;  
  
namespace NewTims  
{  
    public partial class BaseForm : Form  
    {  
        public BaseForm()  
        {  
            InitializeComponent();  
        }  
  
        private void ResizeForm(object sender, EventArgs e)  
        {  
            foreach (Control c in this.Controls)  
            {  
                try  
                {  
                    bool x = default(c.DefaultTop);  
                }  
                catch { }  
            }  
        }  
    }  
}  
  
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,234 questions
0 comments No comments
{count} votes

Accepted answer
  1. ShuaiHua Du 636 Reputation points
    2022-07-30T07:12:16.86+00:00

    Hi,

    The default value expression produces the default value of a type, the default() need a type name or a type parameter in ().

    For example:

    Console.WriteLine(default(int));  // output: 0  
    Console.WriteLine(default(object) is null);  // output: True  
      
    void DisplayDefaultOf<T>()  
    {  
        var val = default(T);  
        Console.WriteLine($"Default value of {typeof(T)} is {(val == null ? "null" : val.ToString())}.");  
    }  
      
    DisplayDefaultOf<int?>();  
    DisplayDefaultOf<System.Numerics.Complex>();  
    DisplayDefaultOf<System.Collections.Generic.List<int>>();  
    // Output:  
    // Default value of System.Nullable`1[System.Int32] is null.  
    // Default value of System.Numerics.Complex is (0, 0).  
    // Default value of System.Collections.Generic.List`1[System.Int32] is null.  
    

    Because c.DefaultTop is a property value, so if you used like default(c.DefaultTop), The compiler displayed an error :"'c' is a variable but is used like a type";

    If the c.DefaultTop is a bool type property, you can use default as below:

    bool x = default(bool);  
    

    For more ,please refer:

    default value expressions (C# reference)

    If right, please Accept.
    Enjoy programming!!!


0 additional answers

Sort by: Most helpful