Hi.
I have a problem with the scope of an object in my C# desktop application for Windows. I would like to instantiate an object and have the object's properties available in my code files behind a number of different windows forms. However, I am seeing CS0103 errors saying "the name does not exist in the current context". I had assumed that because all of the code files use the same namespace, that the object's properties would be available but I've obviously gone wrong somewhere.
namespace TDTestSNWF
{
public partial class Main : Form
{
Transducer newTD = new Transducer(-1);
public Main()
{
InitializeComponent();
newTD.SetTDType(-1);
}using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TDTestSNWF;
namespace TDTestSNWF
{
public partial class frmSelectTestType : Form
{
public frmSelectTestType()
{
InitializeComponent();
}
public void UpdateSelectTestTypeForm()
{
string strTDType;
newTD.SetTDTypeDesc("TEST");
switch (newTD.GetTDType())
{
case 1:
this.Hide();
strTDType = "Non-Smart transducer";
break;
case 2:
strTDType = "Smart transducer";
break;
case 3:
strTDType = "Non-Smart transducer with zero";
break;
default:
strTDType = "Unrecognised transducer type";
break;
}
}The error appears in the second code snip where newTD is referenced.
What am I doing wrong?

Sachin SinghRank #66 · 26.2K reputationPosted Jan 18, 2024, 12:08 PM EST
Modify your code as shown below
namespace TDTestSNWF { public partial class Main : Form { // Make newTD public or use a property to access it from other forms public Transducer newTD = new Transducer(-1); public Main() { InitializeComponent(); newTD.SetTDType(-1); } } }namespace TDTestSNWF { public partial class frmSelectTestType : Form { public frmSelectTestType() { InitializeComponent(); } public void UpdateSelectTestTypeForm() { // Access newTD from Main form Main mainForm = Application.OpenForms.OfType().FirstOrDefault(); if (mainForm != null) { Transducer newTD = mainForm.newTD; newTD.SetTDTypeDesc("TEST"); // Rest of your code } } } }