I have a class called "program" and a data dictionary called "mydic" in this class. Then I tried to write all data from "mydic" dictionary to a file name "expenses.txt". After that, I created another class called "Total_Expenses" that inherit from a "program" class. I tried to read all data from "expenses.txt" and then sorted it in descending order and write to a new file called "expenses_updated". Then I tried to calculate all expenses. But there is an error that stated that "The name "mydic" does not exist in this current context". I tried to create an object of "program" class and access "mydic" dictionary through this object and I also tried to access "mydic" dictionary through class (program.mydic), but none of these worked. Here are my codes:
"program" class:
using System;
using System.IO;
namespace Expense_File
{
public class program
{
public static void Main(String[] args)
{
Console.WriteLine("\n WritingtoFile");
WritingtoFile("d:/expenses.txt");
string filename = Console.ReadLine();
WritingtoFile(filename);
Console.Write("Press any to continue...");
Console.ReadKey();
}
public static void WritingtoFile(string filename)
{
FileStream fs = null;
try
{
fs = new FileStream(filename, FileMode.CreateNew);
}
catch (Exception ex)
{
Console.WriteLine($"Creating new file: {ex.Message}");
return;
}
StreamWriter sw = new StreamWriter(fs);
Dictionary<string, int> mydic = new Dictionary<string, int>()
{
{"Studying",200},
{"Food",500},
{"Picnic",300},
{"Community",50},
{"Others",150}
};
foreach (KeyValuePair<string, int> ele in mydic)
{
sw.WriteLine("{0}: {1}", ele.Key, ele.Value);
}
sw.Close();
Console.WriteLine($"Successfully created new file, {filename}");
}
}
}
"Total_Expenses" class:
using System;
using System.IO;
namespace Expense_File
{
class Total_Expenses:program
{
public static void Main(String[] args)
{
Console.WriteLine("\n WritingtoFile");
WritetoFile("d:/expenses_updated.txt");
string filename = Console.ReadLine();
WritetoFile(filename);
Console.Write("Press any to continue...");
Console.ReadKey();
}
static void WritetoFile(string filename)
{
FileStream fs = null;
try
{
fs = new FileStream(filename, FileMode.CreateNew);
}
catch (Exception ex)
{
Console.WriteLine($"Creating new file: {ex.Message}");
return;
}
StreamWriter sw = new StreamWriter(fs);
var mydic_descen = from ele in mydic
orderby ele.Value descending
select ele;
foreach (KeyValuePair<string, int> ele in mydic_descen)
{
sw.WriteLine("{0}: {1}", ele.Key, ele.Value);
}
int sum = 0;
foreach (KeyValuePair<string, int> ele in mydic_descen)
{
sum = sum + ele.Value;
}
sw.WriteLine("--------------");
sw.WriteLine("Total:" + sum);
sw.Close();
Console.WriteLine($"Successfully created new file, {filename}");
}
}
}