Skip to content

Instantly share code, notes, and snippets.

@AJamesPhillips
Last active August 29, 2019 23:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AJamesPhillips/52f21ca07bf2726f3c784f02fa66f85f to your computer and use it in GitHub Desktop.
Save AJamesPhillips/52f21ca07bf2726f3c784f02fa66f85f to your computer and use it in GitHub Desktop.
C# Redux replica
using System;
//using System.Web.Extensions;
//using System.Web.Script.Serialization;
/************************************************
* State
***********************************************/
public abstract class State<SubClassState>
{
public SubClassState ShallowCopy()
{
return (SubClassState)this.MemberwiseClone();
}
}
public class UserState : State<UserState>
{
public bool signedIn = false;
public string name = "";
public int signIns = 0;
}
public class AppState : State<AppState>
{
public UserState userState = new UserState();
public override string ToString()
{
//return "AppState: " + new JavaScriptSerializer().Serialize(obj);
return "AppState: - " + userState.name + " - " + userState.signedIn + " - " + userState.signIns;
}
}
/************************************************
* Actions
***********************************************/
public class Action
{
}
public class ActionUserSignedIn : Action
{
public string UserName;
}
/************************************************
* Reducers
***********************************************/
public class UserReducer
{
public static UserState Reduce(UserState userState, Action action)
{
//if (action is ActionUserSignedIn ac)
if (action is ActionUserSignedIn)
{
userState = userState.ShallowCopy();
userState.name = ((ActionUserSignedIn)action).UserName;
userState.signedIn = true;
userState.signIns += 1;
}
return userState;
}
}
public class AppReducer
{
public static AppState Reduce(AppState appState, Action action)
{
bool changed = false;
UserState userState = UserReducer.Reduce(appState.userState, action);
changed = changed || userState != appState.userState;
if (changed)
{
appState = appState.ShallowCopy();
appState.userState = userState;
}
return appState;
}
}
/************************************************
* Store
***********************************************/
public class Store
{
AppState appState;
public Store()
{
appState = new AppState();
}
public void Dispatch(Action action)
{
appState = AppReducer.Reduce(appState, action);
}
public AppState GetState()
{
return appState;
}
}
public class Program
{
public static void Main()
{
Store store = new Store();
Console.WriteLine(store.GetState());
store.Dispatch(new ActionUserSignedIn(){ UserName = "Alex" });
Console.WriteLine(store.GetState());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment