How to get data from other class in C#

catalina beaver 41 Reputation points
2022-06-07T08:20:14.707+00:00

Hi,
I'm new to C#. I have two pages in my UWP app. I need to get a data from a variable of other class(page). I always get zero when I try to read the variable. Please have a look at my below code.

namespace PROJECT
{
public sealed partial class MainPage : Page
    {
      public static int var;  // data stores in this variable. 

      public MainPage()
        {
           this.InitializeComponent();
        } 
        public void function()
        {
            var = 4;
        }
    }
}

In the above class. The variable var will set with the value 4. I want to get this data as soon as I navigate to other page. The other class is like below.

namespace PROJECT
{
public sealed partial class SecondPage : Page
    {

      public SecondPage()
        {
           this.InitializeComponent();
           int data = MainPage.var;
          System.Diagnostics.Debug.WriteLine(data); // here I always get 0

        } 
        public void function_secondpage()
        {
             int data = MainPage.var;
             System.Diagnostics.Debug.WriteLine(data); // here I get 4
        }
    }
}

I need to get the data from variavle var as soon as I navigate to the second page. I need to show that data on the second page. However, I always get 0.
I could read the data from the variable var correctly when I call the function function_seconfpage(). However, this wont help me. How can I read the data from varaible var successfully when I navigate to the second page?. Thank you in advance.

Universal Windows Platform (UWP)
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.
6,960 questions
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
2,625 questions
No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 29,236 Reputation points Microsoft MVP
    2022-06-07T08:40:01.9+00:00

    Use a overload for the constructor

    namespace PROJECT
    {
     public sealed partial class SecondPage : Page
     {
     private int _initialValue;
    
           public SecondPage()
           {
                this.InitializeComponent();
    
    
           } 
     public SecondPage(int inComing)
     {
     this.InitializeComponent();
     _initialValue = inComing;
    
               System.Diagnostics.Debug.WriteLine(inComing); // here I always get 0
    
           } 
           public void function_secondpage()
           {
     System.Diagnostics.Debug.WriteLine(inComing); // here I get 4
           }
         }
    }
    
    No comments

0 additional answers

Sort by: Most helpful